Transforming two flat arrays with objects into a nested array is the objective. When an id from list B matches a refId in list A, the object gets appended as a child to the object in list A. This operation results in a new array structured with 2 levels deep, as exemplified.
In List B, there exist objects having ids that correspond to refIds of their sibling objects. In such instances, the code should identify these matches and add them as children of children of the parent object. Consequently, this nesting extends up to 3 levels deep. The nesting process should persist until all possible matches are exhausted.
Is there a modification for the below code to handle nesting at any number of levels, based on matching ids and refIds?
// 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)