javascript-将嵌套的Json转换为带有父ID的纯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附加到每个节点.如果特定节点没有父节点,则其父节点名称应为-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
  }
]

让我知道是否需要进一步的信息.

解决方法:

您可以通过使用一个函数来采取迭代和递归的方法,该函数需要一个数组和一个实际级别的父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; }
上一篇:javascript-如何使用Neo4j Reactivity驱动程序发布/订阅Meteor


下一篇:使用Python重置neo4j中的索引