gpt4 book ai didi

javascript - 有没有办法在javascript中动态创建重复的对象属性结构?

转载 作者:行者123 更新时间:2023-12-02 21:42:58 25 4
gpt4 key购买 nike

我有一个树对象,它基本上只是无限重复的以下对象的数组。

treeNode = {
label: 'Some label',
children: treeNode
}

当用户单击树节点时,我有一个函数可以为单击的节点创建索引数组。基本上类似于 path = [0,3,4,5,1] ,我使用下面的代码使用它来弹出该位置的节点。

pop = tree[path[0]].children[path[1]].children[path[2]].children.pop();

这是有效的,因为我目前知道该函数中的点击深度有多少级。不过,我想让这个动态并以某种循环的方式进行,但我不确定如何做到这一点。例如我想要一个这样的函数:

for(i=0; i<path.length -1; i++){
branches += path[i].children;
}

return tree[branches].pop();

这显然行不通,但我希望能得到一些类似的东西。预先感谢您的帮助。

最佳答案

您可以找到父节点,然后使用splice删除路径中最后一个索引处的节点:

function popPath(tree, path) {
// We need at least one segment
if (!path.length) {
throw new Error("path must have at least one segment");
}

// Find the parent node
let node = tree;
for (let i = 0, len = path.length - 1; i < len; ++i) {
node = node.children[path[i]];
}

// Remove and return the child (which is the first entry in the
// array `splice` returns
return node.children.splice(path[path.length - 1], 1)[0];
}

实例:

const tree = {
label: "Top label",
children: [
{
label: "0 label",
children: [
{
label: "0 0 label",
children: []
},
{
label: "0 1 label",
children: []
},
{
label: "0 2 label",
children: []
},
{
label: "0 3 label",
children: [
{
label: "0 3 0 label",
children: []
},
{
label: "0 3 1 label",
children: [
{
label: "0 3 1 0 label",
children: []
},
{
label: "0 3 1 1 label",
children: []
},
{
label: "0 3 1 2 label",
children: []
}
]
}
]
}
]
}
]
};

function popPath(tree, path) {
// We need at least one segment
if (!path.length) {
throw new Error("path must have at least one segment");
}

// Find the parent node
let node = tree;
for (let i = 0, len = path.length - 1; i < len; ++i) {
node = node.children[path[i]];
}

// Remove and return the child (which is the first entry in the
// array `splice` returns
return node.children.splice(path[path.length - 1], 1)[0];
}

const node = popPath(tree, [0, 3, 1, 1]);
console.log("removed node:", node);
console.log("updated tree:", tree);
.as-console-wrapper {
max-height: 100% !important;
}

关于javascript - 有没有办法在javascript中动态创建重复的对象属性结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60325572/

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