Suppose I have a hierarchy of objects that can have children. All objects have a unique id . I need to get an object from anywhere in this hierarchy if only id is given. For example, a hierarchy might look like this:
var hierarchy = [
{id: 1, children: [
{id: 7},
{id: 8}
]},
{id: 2},
{id: 3, children: [
{id: 9},
{id: 10, children: [
{id: 11},
{id: 12},
{id: 13}
]}
]},
{id: 4},
{id: 5},
{id: 6, children: [
{id: 14}
]}
];
And the function call will look something like this:
retrieveObjectById (10, hierarchy);
// => {id: 10, children: [...]}
I tried writing a function using Array.filter, which would recursively call child elements in a collision, but would also return its ancestors.
source share