我正在迭代地迭代一个潜在的无限嵌套 JSON。
这是我用来执行此操作的功能:
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
}
}
}
这就是我所说的:
var matchedObj = iterate(json,3);
但是,matchedObj
得到的值为undefined
,因为返回值通常来自内部调用iterate()
,而不是直接来自var matchedObj = iterate(json,3);
我现在唯一能看到的方法是在递归函数中使用回调来执行我想要做的任何操作。还有其他方法我错过了吗?
无论如何,这是我的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"
}
]
}
]
答案 0 :(得分:2)
如果找到了结果,你只需要返回递归调用。
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;
}
}
}
}