【问题标题】:Add or Delete particular node in nested JSON Object using javascript使用 javascript 在嵌套 JSON 对象中添加或删除特定节点
【发布时间】:2019-01-25 20:17:42
【问题描述】:

我想制作树状结构。在每个节点中都有两个符号(+ 表示再添加一个节点,- 表示删除特定节点)。我面临的问题是如何从嵌套的 json 中添加/删除节点(子节点)。对于一层或两层嵌套它很好,但对于不止一层,我无法制作一些通用代码来执行此操作。下面是我必须在其上进行添加/删除操作的默认 json 和树的图片。在 HTML 和 CSS 中我没有问题。欢迎一些线索或提示,因为最近 2 天我正在处理这个问题。谢谢

JSON :
{
"name": "abc",
"children": [{
        "name": "def",
        "children": [{
            "name": "jkl",
            "children": [{
                "name": "vwxyz",
                "children": []
            }]

        }]
    },
    {
        "level": "2",
        "name": "ghi",
        "children": [{
            "name": "mno",
            "children": []
        }, {
            "name": "pqr",
            "children": [{
                "name": "stu",
                "children": []
            }]
        }]
    }
]
}

【问题讨论】:

  • 基本上,当您单击 +/- 时,您应该将该函数绑定到一个 json 节点,以便它知道要将子节点添加到哪个节点。
  • 不确定这是否能回答您的问题,但是:github.com/josdejong/jsoneditor
  • 你的意思是从一个节点中删除一个子节点,还是从它的父节点中删除一个节点?
  • @RonyHe 从父节点移除节点
  • name属性是否唯一?

标签: javascript arrays json object nested-object


【解决方案1】:

一种方法是使用 Node 数据结构而不是 JSON。简单的 JS 对象可以在需要时轻松地与 JSON 相互转换。

这样,处理数据就简单多了。 您可以将 DOM 事件连接到节点上的方法并在完成后转换为 JSON

function Node(value, parent) {
    let children = [];

    let self = {
        value: value,
        children: children, 

        // create and return a new node for the value
        add: value => {
            let child = Node(value, self);
            children.push(child);
            return child;
        },

        // remove this node from its parent, if it has one
        remove: () => {
            if (parent !== null && typeof parent !== 'undefined') {
                let indexInParent = parent.children.indexOf(self);
                if (indexInParent > -1) {
                    parent.children.splice(indexInParent, 1);
                }
            }
        },

        // return a plain object that has only data and contains no references to parents
        // JSON.stringify cannot handle circular references
        dataOnly: function () {
            return {
                value: value,
                children: children.map(c => c.dataOnly())
            }
        },

        // return a JSON string for this object
        makeJSON: () => JSON.stringify(self.dataOnly())
    };
    return self;
}


root = Node('lame');
child = root.add('child');
console.log(root.makeJSON());
// logs {"value":"lame","children":[{"value":"child","children":[]}]}

【讨论】:

  • 谢谢 RonyHe 我会试试这个方法
【解决方案2】:

由于您有唯一的名称,您可以创建一个查找对象,其中名称属性作为键,树节点作为其值。然后,您可以快速进入给定名称的任何节点。通过向每个节点对象添加 parent 属性,您可以找到给定节点的父节点。

var data = { name: "abc", ... };
var lookup = {};

function buildLookup(node, parent) {
  node.parent = parent;
  lookup[node.name] = node;
  if (node.children) {
    for (var i = 0; i < node.children.length; i++) {
      buildLookup(node.children[i], node);
    }
  }
}

buildLookup(data, null);
// lookup object now populated

您的 -/+ 按钮可以包含 name 属性以传递给事件处理程序:

<button class="button-plus" data-name="def">+</button>
<button class="button-minus" data-name="def">-</button>

和处理程序:

var addBtns = document.querySelectorAll(".button-plus");
for (var i=0; i < addBtns.length; i++) {
  addBtns[i].addEventListener("click", function (e) {
    var node = lookup[this.dataset.name];
    // create a new empty child
    var child = {
      name: "new child",
      parent: node,
      children: []
    };
    // add it to the children array
    node.children.push(child);
    // add it to the lookup
    lookup[child.name] = child;
  });
}

【讨论】:

  • 谢谢詹姆斯,我会试试这个解决方案
猜你喜欢
  • 2017-08-21
  • 1970-01-01
  • 2019-12-31
  • 2022-07-21
  • 2021-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多