Edgar
Edgar

Reputation: 931

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?

Upvotes: 1

Views: 1090

Answers (2)

Canilho
Canilho

Reputation: 1209

Recursivity is what you are looking for. You need to:

#1 Create a function to receive an object and test if it has anything inside its parent property.

#2 If your object.parent has data, you have to Iterate inside that object. Iterate(OBJ.parent)

#3 If your object has no data, this must be the last element, (return OBJ).

When you solve this problem, you might give a try to solve it again with multiple parents / nodes, and try to print all the elements in the latest nodes

foo: {
        caption: "Italian",
        code: "",
        id: 17,
        parent: {
           caption: "Restaurants",
           code: "",
           id: 9,
           parent:[ {
              caption: "Chairs and Tables",
              code: "chairs_and_tables",
              id: 2,
              parent: ""
           },
           {
              caption: "Food and Drink",
              code: "food_and_drink",
              id: 1,
              parent: ""
          }]
       }
}

Upvotes: 0

user6083184
user6083184

Reputation:

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,[]);

Upvotes: 1

Related Questions