如何从树中删除每个对象

时间:2018-08-31 14:35:16

标签: javascript arrays treeview

我有JSON对象...并想使用Java脚本功能从每个孩子到最后一个孩子删除名称键值,即(name-11,name-22)...

{
  "id": "1",
  "name": "11",
  "child": [
{
  "id": 2,
  "name": "22",
  "child": [
    {
      "id": 3,
      "name": "33",
      "child": [
        {
          "id": 4,
          "name": "44",
          "child": [
            {
              "id": 5,
              "name": "55",
              "child": [
                {
                  "id": 6,
                  "name": "66"
                }
              ]
            }
          ]
        }
      ]
    }
  ]
}
 ]
}

有什么正确的方法吗?

2 个答案:

答案 0 :(得分:1)

可能是这样的...

let myJson = {
  "id": "1",
  "name": "11",
  "child": [{
    "id": 2,
    "name": "22",
    "child": [{
      "id": 3,
      "name": "33",
      "child": [{
        "id": 4,
        "name": "44",
        "child": [{
          "id": 5,
          "name": "55",
          "child": [{
            "id": 6,
            "name": "66"
          }]
        }]
      }]
    }]
  }]
};
let currentObject = myJson;
while (currentObject.child && currentObject.child[0]) {
  delete currentObject.name;
  currentObject = currentObject.child[0];
}
console.log(myJson)

答案 1 :(得分:0)

javascript有一个delete运算符,它的工作原理如下:

n

现在您可以将其与for循环结合使用,并删除每个条目