求修改方法返回一个新的数组对象,不改变原数组(附demo)

题目描述

层级: N层级(不定)
结果:新的对象 - 返回被 checked 为true 的父子节点(根据子项 · 排除未被选中的)
不改变 原对象 arr

题目来源及自己的思路


function isChecked(item, excepetId) {
      if (item.checked) {
        return true;
      } else if (Array.isArray(item.children)) {
        item.children = item.children.filter(subItem => isChecked(subItem));
        return (item.children.length > 0);
      } else {
        return false;
      }
    }
    const newArr = arr.filter(item => isChecked(item));
    console.log(arr);
    console.log(newArr);

相关代码

粘贴代码文本(请勿用截图)

const arr = [
      {
        "id": 4,
        "name": "标题1",
        "children": [
          {
            "id": 3,
            "name": "1-1",
            "children": null
          }
        ]
      },
      {
        "id": 5,
        "name": "标题2",
        "children": [
          {
            "id": 4,
            "name": "2-1",
            "checked": true,
            "children": null
          },
          {
            "id": 5,
            "name": "2-2",
            "checked": true,
            "children": null
          }
        ]
      },
      {
        "id": 7,
        "name": "标题3",
        "children": [
          {
            "id": 6,
            "name": "3-1",
            "checked": true,
            "children": null
          }
        ]
      }
    ];

你期待的结果是什么?实际看到的错误信息又是什么?

求方法返回一个新的数组对象,不改变原数组。

阅读 1.3k
1 个回答

在我看来,你的方法就可以,只不过会改变原数组,所以可以在开始前拷贝一份,这可以使用JSON.string和JSON.parse,直接封装一个方法可以像下面这样写

function getChildren(data){
  return data.reduce((list, item) => {
    if(item.checked){
      list.push(item)
    }else if(Array.isArray(item.children)){
      let children = getChildren(item.children)
      children.length && list.push({
        ...item,
        children
      })
    }
    return list
  }, [])
}

getChildren(arr)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题