How can I push and sort of object array to a tree by typescript or javascript?
I have 3 object arrays from API like this:
const dataParts = [
{
"id": 1,
"title": "Part 1",
"chapterID": [11,12],
"order": 1,
},
{
"id": 2,
"title": "Part 2",
"chapterID": [13],
"order": 2
}
]
const dataChapters = [
{
"id": 11,
"title": "Chapter 1"
"criteriasID": [15,16]
"order": 1,
},
{
"id": 12,
"title": "Chapter 2",
"criteriasID": [],
"order": 2,
},
{
"id": 13,
"title": "Chapter 1",
"criteriasID": [],
"order": 1,
}
]
const dataCriterias = [
{
"id": 15,
"title": "criteria 1",
"order": 1,
},
{
"id": 16,
"title": "criteria 2",
"order": 2,
}
]
How can I push element and sort it by "order" properties?
result I want like this:
const dataTree = [
{
"id": 1,
"title": "Part 1",
"chapterID": [11,12],
"order": 1,
"children": [
{
"id": 11,
"title": "Chapter 1"
"criteriasID": [15, 16]
"order": 1,
"children": [
{
"id": 15,
"title": "criteria 1",
"order": 1,
},
{
"id": 16,
"title": "criteria 2",
"order": 2,
}
]
},
{
"id": 12,
"title": "Chapter 2",
"criteriasID": [],
"order": 2,
"children": []
}
]
},
{
"id": 2,
"title": "Part 2",
"chapterID": [13],
"order": 2,
"children": [
{
"id": 13,
"title": "Chapter 1",
"criteriasID": [],
"order": 1,
}
]
}
]
Do you have any idea about this issue? recursive can do this issue? please help me because this is my thesis graduation
Thanks for your help
You can make use of map
& forEach
loop to get the desired result. Inside map you will find the object & append it to the children property.
const dataParts = [{"id": 1,"title": "Part 1","chapterID": [11,12],"order": 1,},{"id": 2, "title": "Part 2", "chapterID": [13], "order": 2 } ] const dataChapters = [{"id": 11,"title": "Chapter 1","criteriasID": [15,16],"order": 1,},{"id": 12, "title": "Chapter 2", "criteriasID": [], "order": 2, }, { "id": 13, "title": "Chapter 1", "criteriasID": [], "order": 1,} ] const dataCriterias = [{"id": 15,"title": "criteria 1","order": 1,},{"id": 16, "title": "criteria 2", "order": 2, } ]; const find =(arr, obj) => arr.map(a=>obj.find(l=>l.id==a)); const result = dataParts.map(o=>{ let children = find(o.chapterID, dataChapters); children.forEach(t=>{ t.children = find(t.criteriasID, dataCriterias) }); return {...o, children} }); console.log(result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.