[英]map nested array in javascript
我有一个嵌套的对象数组,如下所示:
let data = [
{
id: 1,
title: "Abc",
children: [
{
id: 2,
title: "Type 2",
children: [
{
id: 23,
title: "Number 3",
children:[] /* This key needs to be deleted */
}
]
},
]
},
{
id: 167,
title: "Cde",
children:[] /* This key needs to be deleted */
}
]
我想要的只是递归地找到没有孩子的leaves
(当前是一个空数组)并从中删除 children 属性。
这是我的代码:
normalizeData(data, arr = []) {
return data.map((x) => {
if (Array.isArray(x))
return this.normalizeData(x, arr)
return {
...x,
title: x.name,
children: x.children.length ? [...x.children] : null
}
})
}
您需要为此使用递归:
let data = [{ id: 1, title: "Abc", children: [{ id: 2, title: "Type 2", children: [{ id: 23, title: "Number 3", children: [] /* This key needs to be deleted */ }] }] }, { id: 167, title: "Cde", children: [] /* This key needs to be deleted */ } ] function traverse(obj) { for (const k in obj) { if (typeof obj[k] == 'object' && obj[k] !== null) { if (k === 'children' && !obj[k].length) { delete obj[k] } else { traverse(obj[k]) } } } } traverse(data) console.log(data)
Nik 的回答很好(虽然我没有看到像那样访问children
键的意义),但如果它可以提供帮助,这里有一个更短的替代方案:
let data = [ {id: 1, title: "Abc", children: [ {id: 2, title: "Type 2", children: [ {id: 23, title: "Number 3", children: []} ]} ]}, {id: 167, title: "Cde", children: []} ]; data.forEach(deleteEmptyChildren = o => o.children.length ? o.children.forEach(deleteEmptyChildren) : delete o.children); console.log(data);
如果children
并不总是在那里,您可以将代码的主要部分更改为:
data.forEach(deleteEmptyChildren = o =>
o.children && o.children.length
? o.children.forEach(deleteEmptyChildren)
: delete o.children);
您可以使用递归来做到这一点。
所以这里的基本思想是在removeEmptyChild
函数中,我们检查孩子的长度是否非零。 因此,如果是我们循环遍历 children 数组中的每个元素并将它们作为参数再次传递,如果 children 长度为零,我们将删除 children 键。
let data=[{id:1,title:"Abc",children:[{id:2,title:"Type2",children:[{id:23,title:"Number3",children:[]}]},]},{id:167,title:"Cde",children:[]},{id:1}] function removeEmptyChild(input){ if( input.children && input.children.length ){ input.children.forEach(e => removeEmptyChild(e) ) } else { delete input.children } return input } data.forEach(e=> removeEmptyChild(e)) console.log(data)
只需使用 forEach 进行简单的递归即可。
let data = [{ id: 1, title: "Abc", children: [{ id: 2, title: "Type 2", children: [{ id: 23, title: "Number 3", children: [] /* This key needs to be deleted */ }] }, ] }, { id: 167, title: "Cde", children: [] /* This key needs to be deleted */ } ] const cleanUp = data => data.forEach(n => n.children.length ? cleanUp(n.children) : (delete n.children)) cleanUp(data) console.log(data)
这假设孩子在那里。 如果它可能丢失,则只需要对检查进行微小更改,这样就不会在长度检查中出错。 n.children && n.children.length
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.