Answer the question
In order to leave comments, you need to log in
How to traverse entire tree via array.prototype.reduce?
It is necessary to traverse the entire tree and change the name of the keys, from one name to another. My function changes name to key everywhere except for the last element of the array with the name "Tom"
const data = [
{
name: 'Stas',
age: 40,
children: []
},
{
name: 'Pavel',
age: 40,
children: [
{
name: 'Dmitri',
age: 20,
children:[]
},
{
name: 'Sasha',
age: 15,
children:[
{
name:'Alexey',
age: 34,
children:[]
}
]
}
]
},
{
name: 'Tom',
age: 22,
cildren:[
{
name: 'Hack',
age: 44,
children:[]
},
{
name: 'Hack',
age: 44,
children:[]
}
]
}
]
const traversal= arr =>
(arr || []).reduce((acc,cur,ind,arr)=>{
if(cur.children === undefined){
return acc
} else if(cur.children.length){
acc = [...acc, {key: cur.name, age: cur.age, children: traversal(cur.children)}]
}else{
acc = [...acc, {key: cur.name, age: cur.age, children: cur.children}]
}
return acc
},[])
Answer the question
In order to leave comments, you need to log in
const traversal = (arr, prevKey, key) => arr.map((o) => {
const newObj = {
...o,
[key]: o[prevKey],
children: traversal(o.children, prevKey, key)
};
delete newObj[prevKey];
return newObj;
});
const newArr = traversal(data, 'name', 'key');
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question