Val*_*ter 0 javascript recursion reactjs
假设我有一个深层嵌套的数组,我想获得最深层的嵌套子级,但我想不出实现它的好方法
基本上只要childs属性存在,它就需要在其中潜水,而我不想测试名称是否与我的搜索匹配
[
{
name: 'something',
children: [
{
name: 'something',
children: [
{
...
}
]
}
]
},
{
name: 'something',
children: [
{
name: 'something',
children: [
{
...
}
]
}
]
},
]
Run Code Online (Sandbox Code Playgroud)
hasOwnProperty()可能会帮助您知道该属性是否Children存在,然后知道是否需要递归调用
例如 :
var MyObj = [
{
name: 'something',
children: [
{
name: 'something',
children: [
{
name: 'no child'
},
{
name: 'something empty',
children: [ ]
}
]
}
]
},
{
name: 'something',
children: [
{
name: 'something',
children: [
{
name: 'no child'
}
]
}
]
},
{
name: "children isn't an array",
children: 42
}
]
/*
* This will display in the console the "name" property, if it exists,
* of elements that has :
* - no "children" property
* - a "children" property that isn't an array
* - a "children" property that is an empty array
*/
function ChildrenNames(obj)
{
obj.forEach((subObj) =>
{
if (subObj.hasOwnProperty('children')
&& subObj.children instanceof Array
&& subObj.children.length > 0)
{
ChildrenNames(subObj.children);
}
else
{
if (subObj.hasOwnProperty('name'))
console.log(subObj.name);
}
});
}
ChildrenNames(MyObj);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
72 次 |
| 最近记录: |