1
我有一個包含菜單的對象。迭代遍歷一個對象遞歸查找孩子,沿途拾取父母,祖父母等
我想輸入一個category ID
並得到category name
,然後向後移動以找到它的parents
。在一個對象中這並不容易,所以我想要沿着這個方向趕上parents
。
我遇到的問題是如何在reset
parents
未找到結尾的孩子,並且無處可去。
這就是我想:
var data = [
\t {
"tree_id": "10",
"name": "babies & children",
"parent": null,
"position": "1"
}, {
"tree_id": "2",
"name": "clothing",
"parent": null,
"position": "1",
"children": [{
"tree_id": "15",
"name": "kids",
"parent": "2",
"position": "3",
"children": [{
"tree_id": "78",
"name": "fourToTen",
"parent": "15",
"position": "3",
"children": [{
"tree_id": "102",
"name": "fourToSix",
"parent": "78",
"position": "3"
}]
}]
}]
}, {
"tree_id": "55",
"name": "toys",
"parent": null,
"position": "1",
"children": [{
"tree_id": "35",
"name": "lego",
"parent": "55",
"position": "3"
}]
}
];
var crumbs = [];
function getParts(data, elem) {
for(var i = 0; i < data.length; i++) {
var obj = data[i];
if(obj.children !== undefined){
/* push parent into crumbs */
crumbs.push(obj.name);
\t if(obj.children[0].tree_id === elem){
\t /* if we've found what we're looking, we're done */
crumbs.push(obj.children[0].name);
console.log(crumbs);
} else {
\t /* reset parents */
crumbs = []; /* <-- this is wrong here */
/* not found, keep recursing */
\t getParts(obj.children, elem);
}
}
}
}
/* I want this to return
[
"clothing",
"kids",
"fourToTen",
"fourToSix"
]
but it returns
[
"fourToTen",
"fourToSix"
]
*/
getParts(data, '102');
的問題是,我怎麼能保存parents
陣列直到我在該行的結束和孩子找不到,然後重置它呢?
Here's a fiddle if that's your preferred playround
全局是壞,嘗試讓'wantId'被作爲參數傳遞重寫你的函數。 – georg
確實全球分佈圖很糟糕。 –
已更新回答,留下評論 –