[英]Recursively go through array of objects to create parent child relationships
i have an array of objects looks like this:我有一个对象数组,如下所示:
arr =[{
refno: "1",
name : "section-1"
},{
refno: "1.1",
name : "section-1.1"
},{
refno: "1.1.1",
name : "section-1.1.1"
},{
refno: "1.1.2",
name : "section-1.1.2"
},{
refno: "1.1.3",
name : "section-1.1.3"
},{
refno: "1.2",
name : "section-1.2"
},{
refno: "1.2.1",
name : "section-1.2.1"
}]
i need to convert this array like this:我需要像这样转换这个数组:
[{
"1": {
name: "Section-1",
children: [{
"1.1": {
name: "Section-1.1",
children: [{
"1.1.1": {
name: "Section-1.1.1",
children: []
},
"1.1.2": {
name: "Section-1.1.2",
children: []
},
"1.1.2": {
name: "Section-1.1.3",
children: []
}
}]
},
"1.2": {
name: "Section-1.2",
children: [{
name: "Section-1.2",
children: {
"1.2.1": {
name: "Section-1.2.1",
children: []
}
}
}]
}]
}
}
}]
I have worked hard for it.我已经为之努力了。 The output might differ for yours very slightly.您的输出可能略有不同。 Please check the code and output.请检查代码和输出。 Gist 要旨
var arr =[{ refno: "1", name : "section-1" },{ refno: "1.1", name : "section-1.1" },{ refno: "1.1.1", name : "section-1.1.1" },{ refno: "1.1.2", name : "section-1.1.2" },{ refno: "1.1.3", name : "section-1.1.3" },{ refno: "1.2", name : "section-1.2" },{ refno: "1.2.1", name : "section-1.2.1" }]; function hasKey2(arr, key) { let index = -1; for (let x of arr) { if (x[key] != undefined) { index = x; break; } } return index; } function main(arr) { let output = []; for (let element of arr) { const refno = element.refno; const refArr = element.refno.split("."); let tempArr = output; let markSection = "section-"; for (let ref of refArr) { markSection = markSection + ref; let ind = hasKey2(tempArr, ref); if (ind != -1) { tempArr = ind[ref].children; } else { tempArr.push({ [ref]: { name: markSection, children: [] } }); tempArr = tempArr[tempArr.length - 1][ref].children; } markSection = markSection + "."; } } console.log("Output ", output); return output; } main(arr);
And the output is the following.输出如下。
[{"1":{"name":"section-1","children":[{"1":{"name":"section-1.1","children":[{"1":{"name":"section-1.1.1","children":[]}},{"2":{"name":"section-1.1.2","children":[]}},{"3":{"name":"section-1.1.3","children":[]}}]}},{"2":{"name":"section-1.2","children":[{"1":{"name":"section-1.2.1","children":[]}}]}}]}}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.