1
1
1nsayt2019-10-30 02:07:39
JavaScript
1nsayt, 2019-10-30 02:07:39

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

1 answer(s)
S
Stockholm Syndrome, 2019-10-30
@1nsayt

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');

PS your code doesn't work due to a typo in the property name in the last object

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question