![](/img/trans.png)
[英]Convert array of objects with parent / child relationships to array of nested objects
[英]convert nested tree JSON (parent Child) to an array of objects
我有一个 API,它根据每个对象中的“ParentId”以父/子关系返回 JSON 树格式。 下面是 JSON 的例子
[
{
label: "parentA",
children: [
{
label: "child A 1",
children: [
{ label: "child A 1 - 1", value: "anonymous", children: [] },
],
},
{
label: "child A 2",
children: [{ label: "child A 2-1", children: [] }],
},
],
},
{
label: "parentB ",
children: [
{
label: "child B 1",
children: [{ label: "child B 1-1", children: [] }],
},
],
},
];
其中需要转换为对象数组,其中每个对象将代表节点元素,具有唯一的主键,其中“parentid”为空将是根节点,其他将是其父节点的子节点。
注意:每个元素的 Id 应该是唯一的
最终的对象数组如下
[
{
id: 1,
label: "parentA",
parentId: null,
},
{
id: 2,
label: "child A 1 ",
parentId: 1,
},
{
id: 3,
label: "child A 1 - 1",
parentId: 2,
},
{ id: 4, label: "child A 2", parentId: 1 },
{ id: 5, label: "child A 2-1", parentId: 4 },
{ id: 6, label: "child B", parentId: null },
{ id: 7, label: "child B 1", parentId: 6 },
{ id: 8, label: "child B 1-1", parentId: 7 },
];
我的代码如下,但它的问题是为设置在同一级别的元素返回相同的 ID
let index = 1;
let parentID = result.rows[0].max;
let pushInFinal = (root,parent) => {
root.forEach((item) => {
final_data.push({
id: index ,
label: item.label,
parentId: parent,
});
if (item.hasOwnProperty("children")) {
parentID = index++;
pushInFinal(item.children, parentID);
}
});
};
pushInFinal(data, null);
这一定是一个新的家庭作业。
要将树转换为节点数组,您需要一个简单的递归树遍历:
function flattenTree( tree ) {
return [ ...enumerateNodes( tree ) ];
}
function *enumerateNodes( tree, parent = { id: null } , id = 0 ) {
// construct the flattened tree node
const node = {
...tree,
id: ++id,
parentId: parent.id,
};
delete node.children;
// then yield it
yield node;
// and then, recursively visit each child and yield its results:
for (const childNode of tree.children) {
yield *enumerateNodes(childNode, tree, id);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.