javascript - 将嵌套的 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
}
]
让我知道是否需要任何进一步的信息。
解决方案
您可以通过使用一个函数来采用迭代和递归方法,该函数采用一个数组和一个父 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; }
推荐阅读
- regex - 正则表达式匹配,只要它出现在可选字符之前
- angular - 表单初始化后如何在反应表单上设置默认值?
- javascript - Discord JS 类别和返回 ID
- r - 在某些日期之间替换 R data.frame 的值?
- html - 选择后如何专注于自定义下拉菜单?
- javascript - webpack 不能处理 mathjs 扩展的非 ascii 字符?
- powershell - 创建基于实例执行的方法?
- java - 在 Android Studio 中从 Intent 接收数据时出现问题
- python - 为什么 Pandas 不能将图表中的 X 值识别为 Distinct?
- python - 如何在远程机器人(pyTelegramBotAPI)中处理 inilne_queries?