I currently have this array which repeats recursively:
[ { "Name": "Test", "Children": [ { "Name": "Id", "Property": "Placeholder", "Children": [ { "Name": "Child Id", "Property": "Placeholder", "Children": null } ] } } ]
To get the structure I want I currently have this:
const fixed = data.map(item => item = { data: { name: item.Name, }, children: item.Children.map(child => child = { name: child.Name, }) } )
Is there a way to repeat my initial array.map recursively for each child array?
Advertisement
Answer
One possible solution, based on the output I believe you want:
const array = [{ "Name": "Test", "Children": [{ "Name": "Id", "Property": "Placeholder", "Children": [{ "Name": "Child Id 1", "Property": "Placeholder", "Children": null }, { "Name": "Child Id 2", "Property": "Placeholder", "Children": [{ "Name": "Child Id 3", "Property": "Placeholder", "Children": null }] }] }] }]; const map = (arr) => { return arr ? arr.map(fix) : null; } const fix = (item) => { return { data: { name: item.Name }, children: map(item.Children), }; } console.log(map(array))
Or as suggested below, use shortands:
const map = arr => arr ? arr.map(fix) : null; const fix = item => ({ data: { name: item.Name }, children: map(item.Children), });