skip to Main Content

Here’s an array

const arr = [
  {name: "Earth", id: 1, parent_id: -1},
  {name: "Europe", id: 2, parent_id: 1},
  {name: America": id: 3, parent_id: 1},
  {name: "Asia", id: 4, parent_id: 1}
];

I need to add a hierarchy key to each element of the array, which will contain the array

const arr = [
  {name: "Earth", id: 1, parent_id: -1, hierarchy: ["Earth"]},
  {name: "Europe", id: 2, parent_id: 1, hierarchy: ["Earth", "Europe"]},
  {name: America": id: 3, parent_id: 1, hierarchy: ["Earth", "America"]},
  {name: "Asia", id: 4, parent_id: 1, hierarchy: ["Earth", "Asia"]}
];

I’m trying to do this using lodash find

const parent = _.find(arr, { id: val.parent_id });

    if (parent === undefined) {
      val.hierarchy = [val.id];
    } else {
      val.hierarchy = [...parent.hierarchy, val.id];
    }

But I always get parent === undefined

2

Answers


  1. You don’t need lodash for that. Just collect items into an object and use it to get the path.

    Of course you can use a lodash’s Array#forEach alternative or just for..of loops.

    const arr = [
      {name: "Earth", id: 1, parent_id: -1},
      {name: "Europe", id: 2, parent_id: 1},
      {name: "America", id: 3, parent_id: 1},
      {name: "Asia", id: 4, parent_id: 1},
      {name: "New York", id: 5, parent_id: 3},
    ];
    
    const items = {};
    arr.forEach(item => items[item.id] = item);
    const traverse = item => item ? traverse(items[item.parent_id]).concat(item.name) : [];
    arr.forEach(item => item.hierarchy = traverse(item));
    
    
    arr.forEach(i=>console.log(JSON.stringify(i)));
    .as-console-wrapper{max-height:100%!important}
    Login or Signup to reply.
  2. You could collect all nodes and their parents and build a new array with hierarchies.

    const
        getParents = id => id in references.ids
            ? [...getParents(references.parents[id]), references.ids[id].name]
            : [],
        data = [{ name: "Earth", id: 1, parent_id: -1 }, { name: "Europe", id: 2, parent_id: 1 }, { name: "America", id: 3, parent_id: 1 }, { name: "Asia", id: 4, parent_id: 1 }],
        references = data.reduce((r, o) => {
            r.ids[o.id] = o;
            r.parents[o.id] = o.parent_id;
            return r;
        }, { ids: {}, parents: {} }),
        result = data.map(o => ({ ...o, hierarchy: getParents(o.id) }));
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search