过滤掉深层嵌套的对象并返回一个新对象

时间:2016-10-21 14:29:49

标签: json loops object filter lodash

我有一个4级嵌套对象,看起来像这样

{
  "name": "“Mike”",
  "id": 1000,
  "img": "“#”",
  "children": [
    {
      "name": "“Jack”",
      "id": 1100,
      "img": "#",
      "married": true,
      "children": [
        {
          "name": "”Julia“",
          "id": 1110,
          "img": "#"
        }
      ]
    },
    {
      "name": "”Lily“",
      "id": 1200,
      "img": "#",
      "married": true,
      "children": [
        {
          "name": "”Coco“",
          "id": 1210,
          "img": "#",
          "married": true,
          "children": {
            "name": "”Olivia“",
            "id": 1211,
            "img": "#",
            "married": false
          }
        }
      ]
    }
  ]
}

我有一个idToDisplay = ["1000","1100","1200","1210"]的数组 我想过滤掉ID并省略与idToDisplay不匹配的部分,这样我就可以得到一个像这样的新对象

{
  "name": "“Mike”",
  "id": 1000,
  "img": "“#”",
  "children": [
    {
      "name": "“Jack”",
      "id": 1100,
      "img": "#",
      "married": true,
      ]
    },
    {
      "name": "”Lily“",
      "id": 1200,
      "img": "#",
      "married": true,
      "children": [
        {
          "name": "”Coco“",
          "id": 1210,
          "img": "#",
          "married": true,
        }
      ]
    }
  ]
}

迭代的最佳方法是什么?非常感谢!

1 个答案:

答案 0 :(得分:1)

如果您只是想要就地修改数据,可以像这样递归遍历它:

var data = ... your data ...
var ids = [1000, 1100]
var handleNode = function(node) {
    node.children = node.children.filter(x => ids.includes(x.id))
    node.children.forEach(handleNode)
}
if (!ids.includes(data.id)) {data = {}}
handleNode(data)

之后,您的数据仅包含具有匹配ID的节点。