Edgar Edgar - 2 months ago 10
JSON Question

JSON: Drill down & manipulate nested objects

I have this

foo
object
, it is dynamic object -
foo
object can have a nested
parent
object
which also can have a nested
parent
object
and so on.. In this scenario, what is the best way to:

1) Get the last object that has a parent?

2) Populate an array with all nested parent objects + the first obj (foo.obj)?

foo: {
caption: "Italian",
code: "",
id: 17,
parent: {
caption: "Restaurants",
code: "",
id: 9,
parent: {
caption: "Food and Drink",
code: "food_and_drink",
id: 1,
parent: ""
}
}
};


is it a work for a
while
?

Answer

If you use only vanilla JS.

1a. Approach with loop:

function findLastParent(el) {
    var parent = el,
        notFound = true;
    while (notFound) {
        if (parent.parent) {
            parent = parent.parent
        } else {
            notFound = false;
        }
    }
    return parent;
}

1b. Approach with recursion (be careful with call stack size, cuz every time new function pointer is created):

function findLastParent(el) {
    if (el.parent) {
        return findLastParent(el.parent)
    } else {
        return el
    }
}

2a. Approach with recursion (with loop will be similar to the code from the 1 point):

function getAsArray(el, acc) {
    acc.push(el);
    if (el.parent) {
        return getAsArray(el.parent, acc);
    } else {
        return acc;
    }
}
var result = getAsArray(root,[]);