The goal is to create a new nested array based on 2 flat arrays with objects. If an id from list B matches a refId in list A, the object is added as a child to the object in list A. This creates a new array 2 levels deep as shown in the example.
However in List B, there are objects that have id's that match refId's of their sibling objects. If such is the case the code should find matches and then add them as children of children of parent object. Thus, 3 levels deep. The code should continue to nest until there are no possible matches.
How can the below code be modified to nest any # of levels deep based matching id's and refId's?
// TOP LEVEL
const listA = [
{
"id": 23,
"refId": 23,
"name": 'list A #1',
"isNested": false,
"depth": 1,
"children": []
},
{
"id": 25,
"refId": 25,
"name": 'list A #1',
"isNested": false,
"depth": 1,
"children": []
}
]
// NO HEIRARCHY
const listB = [
{
"id": 23,
"refId": 1234,
"name": "test 1",
"isNested": true,
"depth": 2,
"children": []
},
{
"id": 25,
"refId": 1212,
"name": "test 1",
"isNested": true,
"depth": 2,
"children": []
},
{
"id": 1234,
"refId": 4324,
"depth": 3,
"name": "test 2",
"isNested": true,
"children": []
},
{
"id": 1234,
"refId": 5678,
"depth": 3,
"name": "test 3",
"isNested": true,
"children": []
}
]
const nestedArr = listA.map(
({ id, name, refId, children }) => {
return {
id,
name,
refId,
children: listB.filter((b) => {
return b.id == refId ? b : ''
}),
}
}
)
console.log(nestedArr)