I have an array containing nested objects that need their id property updated by combining all parent names.
The id should be the current node's name value joined with its parents' names, separated by '/'.
treeData = [{
name: 'Infiniti',
id: '',
children: [{
name: 'G50',
id: '',
children: [{
name: 'Pure AWD',
id: ''
},
{
name: 'Luxe',
id: ''
},
],
},
{
name: 'QX50',
id: '',
children: [{
name: 'Pure AWD',
id: ''
},
{
name: 'Luxe',
id: ''
},
],
},
],
},
{
name: 'BMW',
id: '',
children: [{
name: '2 Series',
id: '',
children: [{
name: 'Coupé',
id: ''
},
{
name: 'Gran Coupé',
id: ''
},
],
},
{
name: '3 Series',
id: '',
children: [{
name: 'Sedan',
id: ''
},
{
name: 'PHEV',
id: ''
},
],
},
],
},
];
Expected Result
[{
name: 'Infiniti',
id: 'Infiniti',
children: [{
name: 'G50',
id: 'Infiniti/G50',
children: [{
name: 'Pure AWD',
id: 'Infiniti/G50/Pure AWD'
},
{
name: 'Luxe',
id: 'Infiniti/G50/Luxe'
},
],
},
{
name: 'QX50',
id: 'Infiniti/QX50',
children: [{
name: 'Pure AWD',
id: 'Infiniti/QX50/Pure AWD'
},
{
name: 'Luxe',
id: 'Infiniti/QX50/Luxe'
},
],
},
],
},
{
name: 'BMW',
id: 'BMW',
children: [{
name: '2 Series',
id: 'BMW/2 Series',
children: [{
name: 'Coupé',
id: 'BMW/2 Series/Coupé'
},
{
name: 'Gran Coupé',
id: 'BMW/2 Series/Gran Coupé'
},
],
},
{
name: '3 Series',
id: 'BMW/3 Series',
children: [{
name: 'Sedan',
id: 'BMW/3 Series/Sedan'
},
{
name: 'PHEV',
id: 'BMW/3 Series/PHEV'
},
],
},
],
},
];
I attempted to use Array.prototype.reduce() but struggled to concatenate the previous value.
function updateTreeData(array) {
return array.reduce((returnValue, currentValue) => {
if (currentValue.children != null) {
returnValue.push(Object.assign({}, currentValue, {
children: this.updateTreeData(currentValue.children)
}))
}
return returnValue
}, []);
}
console.log(updateTreeData(treeData))