提问人:testerprox 提问时间:11/17/2022 最后编辑:testerprox 更新时间:11/17/2022 访问量:41
将最后一个元素从深层嵌套对象保存到非全局数组
Save last elements from deep nested object to a non global array
问:
我已经知道了,如何获取深度嵌套对象的最后一个元素。 有关工作示例,请参阅此处:如何在包含对象的深度嵌套数组中获取最后一个子项
现在我不想像示例中那样记录名称,而是想将它们保存在一个数组中,该数组不应该是全局的。我只想要一个函数返回这个数组。
如果不为此声明全局数组,这在某种程度上是可能的吗?console.log(subObj.name)
这是我的代码:
function childrenNames (obj) {
var lastChildren = [];
obj.forEach((subObj) => {
if (subObj.hasOwnProperty('specification') && subObj.specification instanceof Array && subObj.specification.length > 0) {
childrenNames(subObj.specification);
} else {
if (subObj.hasOwnProperty('name')) {
lastChildren.push(subObj.name)
}
}
})
console.log(lastChildren);
return lastChildren
}
但它只是返回 4 个不同的数组,而不是 1 个包含所有最后的孩子。
答:
-1赞
user3425506
11/17/2022
#1
我不确定这是否是一个有效的答案,我不明白它,但我现在把它留在这里,因为它至少从表面上看确实可以回答这个问题。据我所知,它不需要声明全局数组吗?
var obj = [
{
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
}
]
function childrenNames (obj) {
var lastChildren = [];
obj.forEach((subObj) => {
if (subObj.hasOwnProperty('specification') && subObj.specification instanceof Array && subObj.specification.length > 0) {
childrenNames(subObj.specification);
} else {
if (subObj.hasOwnProperty('name')) {
lastChildren.push(subObj.name)
}
}
})
// console.log(lastChildren);
return lastChildren
}
const res = childrenNames(obj);
console.log('res', res);
评论
0赞
user3425506
11/17/2022
@Bergi 你认为这是一个可以接受的答案吗?从不全球化的角度来看
0赞
testerprox
11/17/2022
嘿,你能解释一下包装器在这里做什么吗?我想知道,因为该函数没有被调用
0赞
user3425506
11/17/2022
我将尝试通过编辑答案来解释我认为它正在做什么,以便它与代码一起。
0赞
user3425506
11/17/2022
@testerprox我现在完全困惑了。我以为我在打电话,但从片段来看,我没有在任何地方调用包装器。我不明白为什么childrensNames正在运行,因为它没有被调用,更不用说为什么它似乎在工作。很抱歉造成混乱!const res = wrapper(childrensNames, obj);
0赞
user3425506
11/17/2022
我完全困惑了,会改变我的答案吗?!
评论