gpt4 book ai didi

javascript - 如何获取带有对象的深度嵌套数组中的最后一个子元素

转载 作者:行者123 更新时间:2023-11-28 12:54:52 31 4
gpt4 key购买 nike

假设我有一个深度嵌套的数组,我想要获得最深嵌套的子数组,但我无法想出实现它的好方法

基本上,只要 child 属性存在,它就需要深入其中,但我不想测试名称是否与我的搜索匹配

[
{
name: 'something',
children: [
{
name: 'something',
children: [
{
...
}
]
}
]
},
{
name: 'something',
children: [
{
name: 'something',
children: [
{
...
}
]
}
]
},
]

最佳答案

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);

关于javascript - 如何获取带有对象的深度嵌套数组中的最后一个子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56756192/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com