1
鉴于对象数组这样任何级别删除项目:在JS嵌套的对象阵列
var items = [{
id: 1
}, {
id: 2,
child: {
id: 3
}
}, {
id: 4,
child: {
id: 5,
child: {
id: 6
}
}
}];
我需要一种方法在任何水平,以除去一个项目。这段代码做我想要的,但有没有更好的方法?
最初我尝试使用一个递归函数来做,但无法让它工作。
var removed = removeItems(items, 5);
print(removed);
function removeItems(items, id) {
items.forEach(function(item, index, allItems) {
if (item.id === id) {
items.splice(index, 1);
}
if (item.child) {
item = testChild(item, item.child, id);
}
});
return items;
}
function testChild(parent, child, id) {
if (child.id === id) {
delete parent.child
return parent;
} else {
if (child.child) {
return testChild(child, child.child, id);
}
return parent;
}
}
function print(obj) {
document.querySelector('#out').innerHTML += JSON.stringify(obj, null, 2);
}
的jsfiddle:https://jsfiddle.net/syvf46uL/12/
谢谢EyuelDK –