gpt4 book ai didi

javascript - 删除对象数组中的所有 child

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:42:12 26 4
gpt4 key购买 nike

var arr = [{
"id": "1",
"name": "News",
}, {
"id": "3",
"parent": "1",
"name": "News 2"
}, {
"id": "5",
"parent": "3",
"name": "News",
}, {
"id": "7",
"parent": "5",
"name": "News 2"
}, {
"id": "15",
"name": "News 2"
}, {
"id": "20",
"name": "News 2"
}];

var deleted_id = 1;

for (var i = 0; i < arr.length; i++) {
if (arr[i].parent == deleted_id) {
arr.splice(i, 1);
} else continue;
}

我需要删除项目(例如 ID:“1”)。我还需要删除所有级别的 child ,他们的“父”字段与已删除项目的 ID 相同。

请注意,id 为 3 的项是 id 为 5 的项的父项,id 为 5 的项是 id 为 7 的项的父项。它们都应该被删除。

有一些深层次,因此,结果应该是:

[{
"id": "15",
"name": "News 2"
}, {
"id": "20",
"name": "News 2"
}]

最佳答案

首先你应该找到层级关系。然后根据要删除的 id 去寻找它的子项并用父项删除它们。

var arr = [{"id": "1", "name": "News", }, {"id": "3", "parent": "1", "name": "News 2"}, {"id": "5", "parent": "3", "name": "News", }, {"id": "7", "parent": "5", "name": "News 2"}, {"id": "15", "name": "News 2"}, {"id": "20", "name": "News 2"}];

console.clear();

var children = {};
arr.forEach(function (item) {
if (item.parent)
children[item.parent] = (children[item.parent] || []).concat(item.id);
});
function deleteItem(id) {
if (children[id])
children[id].forEach(deleteItem)
var index = arr.findIndex(i => i.id === id);
if (index >= 0)
arr.splice(index, 1);
}

deleteItem('1')
console.log(arr);

关于javascript - 删除对象数组中的所有 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38375275/

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