首页 > 解决方案 > 如何递归地将对象键值对添加到具有子数组的对象数组中?

问题描述

我仍在学习递归的技巧,我想在这个嵌套的数组树中的每个对象中添加“isChecked:false”。

const nestedMap = (arr) => {
  const result = arr.map(row => {
    if (row.children.length) {
      const children = row.children.map(child => {
        return { ...child, isChecked: false };
      });
      return { ...row, isChecked: false, children };
    } else {
      return { ...row, isChecked: false };
    }
  });
  return result[0].children[0]
}

nestedMap([{title: 'page1', children: [{title: 'page2', children: [{title: 'page4'}]}, {title: 'page3'}]}, {title: 'page5', children: []}])

这是我的结果 - 正如你所看到的,我成功地更新了第一组孩子,但没有更新其余的孩子。

{ title: 'page2',
  children: [ { title: 'page4' } ],
  isChecked: false } 

我知道我应该在其内部的某个地方调用该函数,但我是个白痴。与往常一样,我们将不胜感激任何帮助。谢谢你。

标签: javascriptarraysrecursionjavascript-objects

解决方案


您的 if 语句if (row.children.length) {检查是否row.children是一个长度 > 0 的数组,所以这里是您想nestedMap再次调用的地方。

尝试这样的事情:

const nestedMap = (arr) => {
  const result = arr.map(row => {
    // check if row.children exists AND if its length exists / is greater than 0
    if (row.children && row.children.length) {
      const children = nestedMap(row.children);
      return { ...row, isChecked: false, children };
    } else {
      return { ...row, isChecked: false };
    }
  });
  // Note: You should probably return the entire result here, not result[0].children[0]
  return result;
}

let output = nestedMap([{title: 'page1', children: [{title: 'page2', children: [{title: 'page4'}]}, {title: 'page3'}]}, {title: 'page5', children: []}])

console.log(output)

请注意,我做了 3 处更改:

  1. if (row.children && row.children.length) {
    • 在检查之前,我添加了检查以确保row.children存在row.children.length
  2. const children = nestedMap(row.children);
    • 这是我们进行递归的地方:)
  3. return result;
    • 这将返回整个结果(原始嵌套的对象数组,isChecked: false每个对象中都有)。
    • 注意:我不确定你为什么用 结束你的函数result[0].children[0],它只会返回原始数组的第一个项目的第一个孩子?

推荐阅读