You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将JS嵌套数组中的字符串替换为工厂生成的对象(精简函数式实现)

用函数式风格精简处理嵌套配置对象的小技巧

嘿,我来给你梳理下怎么用函数式的方式搞定这个需求,既精简代码又符合函数式无副作用、纯函数的核心原则~

核心思路就是写一个递归的纯函数,遍历你的配置对象,把所有嵌套层级里children数组中的字符串,替换成DummyFactory生成的对象,而且完全不会修改原始的配置对象,操作起来非常干净。

完整实现代码

const myConfigObject = { 
  label: 'something', 
  children: [ 
    { id: 'one', style: 'some style', children: ['key1', 'key2'] }, 
    { id: 'two', style: 'some other style', children: ['key3', 'key4'] }, 
  ] 
};

function DummyFactory(key) { 
  return { id: key, data: 'generated data' };
}

// 递归转换的纯函数:不修改原对象,返回全新转换后的对象
const transformConfig = (config) => {
  // 处理数组:元素是字符串就传入工厂生成对象,是对象就递归处理
  if (Array.isArray(config)) {
    return config.map(item => 
      typeof item === 'string' ? DummyFactory(item) : transformConfig(item)
    );
  }
  // 处理对象:复制所有原属性,仅当存在children时再做转换
  if (typeof config === 'object' && config !== null) {
    return {
      ...config,
      ...(config.children && { children: transformConfig(config.children) })
    };
  }
  // 非数组/对象类型直接返回
  return config;
};

// 调用函数得到转换后的配置
const transformedConfig = transformConfig(myConfigObject);
console.log(transformedConfig);

代码亮点说明

  • 纯函数设计:完全不修改原始的myConfigObject,所有操作都返回新对象,后续维护和调试都更省心,符合函数式编程的核心思想。
  • 自动适配嵌套深度:不管你的配置对象有多少层children嵌套,这个递归函数都能自动处理,不用手动写多层遍历逻辑。
  • 精简高效:用ES6扩展运算符(...)和map方法简化对象复制与数组遍历,代码简洁且可读性拉满。

若结构固定为两层嵌套?

要是你明确知道配置不会有更深的嵌套,还能再精简成非递归版本,代码更短:

const transformShallow = (config) => ({
  ...config,
  children: config.children.map(child => ({
    ...child,
    children: child.children.map(key => DummyFactory(key))
  }))
});

这个版本只处理当前层级的children,适合结构固定的场景。

转换后的最终效果

最终得到的transformedConfig结构如下:

{
  label: 'something',
  children: [
    {
      id: 'one',
      style: 'some style',
      children: [
        { id: 'key1', data: 'generated data' },
        { id: 'key2', data: 'generated data' }
      ]
    },
    {
      id: 'two',
      style: 'some other style',
      children: [
        { id: 'key3', data: 'generated data' },
        { id: 'key4', data: 'generated data' }
      ]
    }
  ]
}

内容的提问来源于stack exchange,提问作者SoluableNonagon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:50:54