具有深层嵌套的对象映射

时间:2019-07-20 07:47:33

标签: javascript arrays object

我有一个对象:

const object = {
  children: [{
    uuid: '1',
    children: [{
        uuid: '2',
        children: [{
            uuid: '3',
            children: []
          },
          {
            uuid: '4',
            children: [{
              uuid: '5',
              children: []
            }]
          }
        ]
      },
      {
        uuid: '6',
        children: []
      }
    ]
  }]
}

我需要一个可以映射每个孩子的函数:

JavaScript

deepMapChildren(object, (child) => ({...child, uuid: 'new uuid'}))

有人为此编写脚本吗?是否知道执行此操作的内置方法?

1 个答案:

答案 0 :(得分:1)

此解决方案对每个孩子递归调用deepMapChildren来更新孩子,也就是孩子。该函数使用带休息的解构将children与当前子项分开。然后,它将对回调应用cb应用于子项并使用deepMapChildren映射子项的结果进行扩散。

const deepMapChildren = (obj, cb, childrenKey = 'children') => {
  const { [childrenKey]: children = [], ...child } = cb(obj); // update the child, and seperate the child's content and it's children
  
  return {
    ...child,
    [childrenKey]: children.map(c => deepMapChildren(c, cb)) // map the children (if any)
  };
}

const object = {"children":[{"uuid":"1","children":[{"uuid":"2","children":[{"uuid":"3","children":[]},{"uuid":"4","children":[{"uuid":"5","children":[]}]}]},{"uuid":"6","children":[]}]}]}

const result = deepMapChildren(object, (child) => 
  ({...child, uuid: 'new uuid'})
)

console.log(result)