-2
我想知道JSON對象中的遞歸鍵。例如,JSON對象就像基於JSON值獲取密鑰
{
"Division1" : {
"checked": true,
"level": 1,
"District1-1": {
"checked": true,
"level": 2,
"Area1-1-1": {
"checked": true,
"level": 3,
"Project1-1-1-1": {
"checked": true,
"level": 4
}
},
"Area1-1-2": {
"checked": true,
"level": 3,
"Project1-1-2-1": {
"checked": true,
"level": 4,
"05": {
"checked": true,
"level": 5
}
}
}
}
}
}
,我能夠找到「Project1-1-1-1」,我應該能夠找到並存儲「Area1-1-1」如何執行遞歸搜索來存儲父/祖父鍵?「District1-1」,「Division1」在數組中,
我使用JavaScript來實現這一點
當前JS:
var parent = [];
$.test.getObjects = function(obj, key, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)){ continue; }
if (typeof obj[i] == 'object') {
// console.log(i);
parent.push(i);
objects = objects.concat($.test.getObjects(obj[i], key, val));
}
//if key matches and value matches or if key matches and value is not passed (eliminating the case where key matches but passed value does not)
if (i == key && obj[i] == val || i == key && val == '') { //
objects.push({"parent": parent,"children": obj});
} else if (obj[i] == val && key == ''){
//only add if the object is not already in the array
if (objects.lastIndexOf(obj) == -1){
objects.push({"parent": parent,"children": obj});
}
}
}
return objects;
};
你可以添加你必須找到的代碼** Project1-1-1-1 **? – funkwurm 2014-09-03 09:51:47
問題是什麼? 「存儲父母/祖父母鑰匙」是什麼意思? – 2014-09-03 09:55:17
@funkwurm我已更新問題 – cs1193 2014-09-03 09:58:43