[英]convert nested tree JSON (parent Child) to an array of objects
I have an API which returns JSON tree format in parent/child relationship based on "ParentId" in each object.我有一个 API,它根据每个对象中的“ParentId”以父/子关系返回 JSON 树格式。 Below is the example of 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: [] }],
},
],
},
];
Which need to be converted into array of object where each object will represent the node element, with a unique primary key,Where "parentid" is null it will be root nodes and other will be child node of their parent node.其中需要转换为对象数组,其中每个对象将代表节点元素,具有唯一的主键,其中“parentid”为空将是根节点,其他将是其父节点的子节点。
NOTE: the Id for each element should be unique注意:每个元素的 Id 应该是唯一的
the final array of objects as bellow最终的对象数组如下
[
{
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 },
];
my code is as below but the issue with it is returning the same id's for the elements which setting on the same level我的代码如下,但它的问题是为设置在同一级别的元素返回相同的 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);
This must be a new homework assignment.这一定是一个新的家庭作业。
To convert a tree into an array of nodes, you need a simple recursive tree-walk:要将树转换为节点数组,您需要一个简单的递归树遍历:
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.