I have an array of nested objects. I need to update the id property of each node by concatenating all its parent names.
id should be value of the name property of current node joined with name property od it's parents 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 Outcome
[{
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 tried to use Array.prototype.reduce(), but I am unable to get the previous value to concatinate.
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))
CodePudding user response:
You can try the recursion approach
const 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:""}]}]}];
const populateId = (list, currentId) => {
for(const item of list) {
if(!currentId) {
item.id = item.name
} else {
item.id = currentId '/' item.name
}
if(item.children) {
populateId(item.children, item.id)
}
}
}
populateId(treeData)
console.log(treeData)