简体   繁体   中英

How to iterate through a list using recursion

I've got a list like this below and I'm trying to get a list of all subnodes. I need to find all children and subchildren of a list. In this case it should return exact this list.

const data = [
  {
    id: 1,
    parent: 0,
  },
  {
    id: 2,
    parent: 1,
  },
  {
    id: 3,
    parent: 1,
  },
  {
    id: 4,
    parent: 3,
  }
];

I'm trying to choose whether or not call the function again in many ways but the result is always wrong.

const getNodes = (n) => {
   
  let family = [];
  for (let i of n) {
    const sons = data.filter(x => x.parent === i.id); 
    if (sons.length !== 0) {
      family.push(getNodes(sons));
    } else {
      family.push(i);
    }
  }
  return family;
};

console.log(getNodes([data[0]]));

Let's transform that to a tree.

 const data = [{ id: 1, parent: 0, }, { id: 2, parent: 1, }, { id: 3, parent: 1, }, { id: 4, parent: 3, } ]; // first obj of nodes grouped by id var obj_nodes = data.reduce(function(agg, item) { agg[item.id] = {...item, children: [] }; return agg; }, {}) // console.log(obj_nodes) // connecting edges (child parent relations) data.forEach(function(item) { var source = obj_nodes[item.id]; var destination = obj_nodes[item.parent]; destination && destination.children.push(source); }, {}) var trees = Object.values(obj_nodes); var result = trees[0] console.log(result)
 .as-console-wrapper {max-height: 100% !important}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM