题目描述
层级: 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
}
]
}
];
你期待的结果是什么?实际看到的错误信息又是什么?
求方法返回一个新的数组对象,不改变原数组。
在我看来,你的方法就可以,只不过会改变原数组,所以可以在开始前拷贝一份,这可以使用JSON.string和JSON.parse,直接封装一个方法可以像下面这样写