繁体   English   中英

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

[英]Is there a way to dynamically create a repeating object property structure in javascript?

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

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; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM