2
{"func" : "sprint", "nest" : {"func" : "walk", "nest": {"func" : "run"}}}

Above is an example of a nested Json object.

These can range from a single object to many nested objects. I want to call method based on the most nested object to the least nested.

In the example there is 2 nest values. How can I call the last one to the first in this order

func : run

than

func : walk

than

func : sprint

1 Answer 1

6

You could take a recursive depth-first search for the nested object.

function depthFirst(object) {
    return [...(object.nest ? depthFirst(object.nest) :[]), object.func];
}

var data = { func: "sprint", nest: { func: "walk", nest: { func: "run" } } };

console.log(depthFirst(data));

Sign up to request clarification or add additional context in comments.

2 Comments

I haven't seen something like this before, Do you have a good link so I can read up depthFirst, Also in the return statement what is the 3 periods for?
spread syntax ... returns the items of iterables as parameters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.