首页 > 解决方案 > 将嵌套的 Json 转换为带有 parentId 的平面 Json 到每个节点

问题描述

以下 Json 结构是 Neo4J apoc 查询的结果。我想将此嵌套的 Json 转换为平面 Json 结构,如第二个 json 所示。

[
    {
      "child1": [
        {
          "_type": "EntityChild1",
          "name": "Test222",
          "_id": 2
        }
      ],
      "child2": [
        {
          "_type": "EntityChild2",
          "name": "Test333",
          "_id": 3,
          "child2_child1": [
            {
              "_type": "EntityChild2_1",
              "name": "Test444",
              "_id": 6,
              "child2_child1_child1": [
                {
                  "_type": "EntityChild2_1_1",
                  "name": "Test555",
                  "_id": 7
                }
              ]
            }
          ]
        }
      ],
      "_type": "EntityParent",
      "name": "Test000",
      "_id": 1,
      "child3": [
        {
          "_type": "EntityChild3",
          "name": "Test111",
          "_id": 4
        }
      ],
      "child4": [
        {
          "_type": "EntityChild4",
          "name": "Test666",
          "_id": 5
        }
      ]
    }
    ]

这是我正在寻找的结果,我还希望将 parentId 附加到每个节点。如果特定节点没有父节点,则它的 parentid 应为 -1。

[
  {
    "_type": "EntityParent",
    "name": "Test000",
    "_id": 1,
    "parentid": -1
  },
  {
    "_type": "EntityChild1",
    "name": "Test222",
    "_id": 2,
    "parentid": 1
  },
  {
    "_type": "EntityChild2",
    "name": "Test333",
    "_id": 3,
    "parentid": 1
  },
  {
    "_type": "EntityChild2_1",
    "name": "Test444",
    "_id": 6,
    "parentid": 3
  },
  {
    "_type": "EntityChild2_1_1",
    "name": "Test555",
    "_id": 7,
    "parentid": 6
  },
  {
    "_type": "EntityChild3",
    "name": "Test111 ",
    "_id": 4,
    "parentid": 1
  },
  {
    "_type": "EntityChild4",
    "name": "Test666",
    "_id": 5,
    "parentid": 1
  }
]

让我知道是否需要任何进一步的信息。

标签: javascriptjsontypescriptneo4j

解决方案


您可以通过使用一个函数来采用迭代和递归方法,该函数采用一个数组和一个父 id 作为实际级别。

如果一个属性以 开头child,它会使用实际值再次调用该函数_id并将所有项目推送到结果集中。

function getFlat(array, parentid) {
    return array.reduce((r, o) => {
        var temp = {};
        r.push(temp);
        Object.entries(o).forEach(([k, v]) => {
            if (k.startsWith('child')) {
                r.push(...getFlat(v, o._id));
            } else {
                temp[k] = v;
            }
        });
        temp.parentid = parentid;
        return r;
    }, []);
}


var data = [{ child1: [{ _type: "EntityChild1", name: "Test222", _id: 2 }], child2: [{ _type: "EntityChild2", name: "Test333", _id: 3, child2_child1: [{ _type: "EntityChild2_1", name: "Test444", _id: 6, child2_child1_child1: [{ _type: "EntityChild2_1_1", name: "Test555", _id: 7 }] }] }], _type: "EntityParent", name: "Test000", _id: 1, child3: [{ _type: "EntityChild3", name: "Test111", _id: 4 }], child4: [{ _type: "EntityChild4", name: "Test666", _id: 5 }] }],
    flat = getFlat(data, -1);

console.log(flat);
.as-console-wrapper { max-height: 100% !important; top: 0; }


推荐阅读