I'm iterating over a potentially infinitely-nested JSON recursively.
This is the function I use to do this:
function iterate(obj,matchId) {
for(var key in obj) {
var elem = obj[key];
if(obj.id == matchId) { //if objects id matches the arg I return it
console.log(obj); // matched obj is always logged
return(obj);
}
if(typeof elem === "object") { // is an object (plain object or array),
// so contains children
iterate(elem,matchId); // call recursively
}
}
}
And this is how I call it:
var matchedObj = iterate(json,3);
However, matchedObj
get's value undefined
since the return value usually comes from calling iterate()
from within itself and not directly by var matchedObj = iterate(json,3);
Only way I can see now is to use a callback from within the recursive function to perform whatever action I want to do. Is there any other way I'm missing?
In any case, this is my JSON:
var json = [
{
"id": 1,
"text": "Boeing",
"children": [
{
"id": 2,
"text": "747-300",
"json": "737 JSON"
},
{
"id": 3,
"text": "737-400",
"json": "737 JSON"
}
]
},
{
"id": 4,
"text": "Airbus",
"children": [
{
"id": 5,
"text": "A320",
"json": "A320 JSON"
},
{
"id": 6,
"text": "A380",
"json": "A380 JSON"
}
]
}
]
You just need to return the recursive call if it found the result.
function iterate(obj,matchId) {
for(var key in obj) {
var elem = obj[key];
if(obj.id == matchId) { //if objects id matches the arg I return it
console.log(obj); // matched obj is always logged
return(obj);
}
if(typeof elem === "object") { // is an object (plain object or array),
// so contains children
var res = iterate(elem,matchId); // call recursively
if (res !== undefined) {
return res;
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.