如何从树中删除每个对象[重复]

问题描述 投票:0回答:2

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

{
  "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"
                }
              ]
            }
          ]
        }
      ]
    }
  ]
}
 ]
}

有没有正确的方法呢?

javascript arrays treeview
2个回答
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)

0
投票

javascript有一个删除操作符,它的工作方式如下:

delete object.name

现在你可以将它与for循环一起使用并删除每个条目

© www.soinside.com 2019 - 2024. All rights reserved.