{"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
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));
answered Sep 9, 2019 at 15:06
Nina Scholz
388k26 gold badges367 silver badges417 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
user3277468
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?
Nina Scholz
spread syntax
... returns the items of iterables as parameters.lang-js