有没有一种方法可以在javascript中动态创建重复的对象属性结构



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

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

当用户单击树节点时,我有一个函数可以为单击的节点创建一个索引数组。基本上类似路径=[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;
}

最新更新