我有一个嵌套的对象数组,如下所示:
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
(当前是一个空数组),并从其中删除子项属性。
这是我的代码:
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
}
})
}
答案 0 :(得分:4)
您需要为此使用递归:
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)
答案 1 :(得分:3)
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);
答案 2 :(得分:2)
您可以使用递归来做到这一点。
因此,这里的基本思想是在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)
答案 3 :(得分:2)
只需使用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