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
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 justfor..of
loops.You could collect all nodes and their parents and build a new array with hierarchies.