gpt4 book ai didi

javascript - 从深度嵌套的对象数组中删除匹配的对象

转载 作者:行者123 更新时间:2023-11-28 17:08:44 26 4
gpt4 key购买 nike

我有一个带有子项的数据树结构:

{  id: 1,
name: "Dog",
parent_id: null,
children: [
{
id: 2,
name: "Food",
parent_id: 1,
children: []
},
{
id: 3,
name: "Water",
parent_id: 1,
children: [
{
id: 4,
name: "Bowl",
parent_id: 3,
children: []
},
{
id: 5,
name: "Oxygen",
parent_id: 3,
children: []
},
{
id: 6,
name: "Hydrogen",
parent_id: 3,
children: []
}
]
}
]
}

这表示一个 DOM 结构,用户可以通过单击 DOM 中的相应按钮来选择要删除的项目。

我有一个已知的所选项目的文本标题,要从 DOM 中删除,设置为变量 clickedTitle。我无法找到一种算法来允许我从深度嵌套的树中删除正确的对象数据。

这是我的代码:

function askUserForDeleteConfirmation(e) {
const okToDelete = confirm( 'Are you sure you want to delete the item and all of its sub items?' );
if(!okToDelete) {
return;
}
const tree = getTree(); // returns the above data structure
const clickedTitle = getClickedTitle(e); // returns string title of clicked on item from DOM - for example "Dog" or "Bowl"
const updatedTree = removeFromTree(tree, tree, clickedTitle);

return updatedTree;
}

function removeFromTree(curNode, newTree, clickedTitle) {
if(curNode.name === clickedTitle) {
// this correctly finds the matched data item to delete but the next lines don't properly delete it... what to do?
const index = curNode.children.findIndex(child => child.name === clickedTitle);
newTree = curNode.children.slice(index, index + 1);
// TODO - what to do here?
}

for(const node of curNode.children) {
removeFromTree(node, newTree, clickedTitle);
}

return newTree;
}

我尝试使用 Removing matched object from array of objects using javascript 中的信息没有成功。

最佳答案

如果你不介意修改参数树in-place ,这应该可以完成工作。请注意,它将返回 null如果您尝试删除根。

const tree = { id: 1, name: "Dog", parent_id: null, children: [ { id: 2, name: "Food", parent_id: 1, children: [] }, { id: 3, name: "Water", parent_id: 1, children: [ { id: 4, name: "Bowl", parent_id: 3, children: [] }, { id: 5, name: "Oxygen", parent_id: 3, children: [] }, { id: 6, name: "Hydrogen", parent_id: 3, children: [] } ] } ] };

const removeFromTree = (root, nameToDelete, parent, idx) => {
if (root.name === nameToDelete) {
if (parent) {
parent.children.splice(idx, 1);
}
else return null;
}

for (const [i, e] of root.children.entries()) {
removeFromTree(e, nameToDelete, root, i);
}

return tree;
};

console.log(removeFromTree(tree, "Oxygen"));

您当前的代码非常正确。但是:

newTree = curNode.children.slice(index, index + 1);

强调了几个问题:我们需要操纵父级的children要删除的数组 curNode而不是curNode自己的children大批。我通过调用递归地传递父对象和子索引,省去了线性操作的麻烦findIndex .

此外,从 index 进行切片至index + 1只提取一个元素并且不修改curNode.children 。如何使用 newArray 并不明显或通过调用堆栈返回它。 splice似乎是一种更适合当前任务的工具:就地提取一个元素。

请注意,此函数将删除与 nameToDelete 匹配的多个条目.

关于javascript - 从深度嵌套的对象数组中删除匹配的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55082961/

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