在多维JSON中查找值/字符串及其父级/子级



我有这个JSON:

{
"San Jose" :  {
"Moravia" : {
"San Vicente" : "san_vicente",
"La Trinidad" : "la_trinidad",
"Los Colegios" : "los_colegios"
},
"Desamparados" : {
"San Miguel" : "san_miguel",
"Gravilias" : "gravilias",
"Damas" : "damas"
},
"Curridabat" : {
"Granadilla" : "granadilla",
"Sanchez" : "sanchez",
"Tirrases" : "tirrases"
}
},
"Cartago" : {
"Oreamuno" : {
"Cot" : "cot",
"Cipreses" : "cipreses",
"Santa Rosa" : "santa_rosa"
},
"La Union" : {
"Tres Rios" : "tres_rios",
"Dulce Nombre" : "dulce_nombre",
"Concepcion" : "concepcion"
},
"Turrialba" : {
"La Suiza" : "la_suiza",
"Peralta" : "peralta",
"La Isabel" : "la_isabel"
}
},
"Puntarenas" : {
"Golfito" : {
"Puerto Jimenez" : "puerto_jimenez",
"Guaycara" : "guaycara",
"Pavon" : "pavon"
},
"Coto Brus" : {
"San Vito" : "san_vito",
"Limoncito" : "limoncito",
"Agua Buena" : "agua_buena"
},
"Corredores" : {
"La Cuesta" : "la_cuesta",
"Paso Canoas" : "paso_canoas",
"Laurel" : "laurel"
}
}
}

我想得到一个特定的值和他相应的父母/孩子。例如:

var value = json.get("Cot");
var child =  value.child();

或者:

var value = json.get("Cot");
var parent =  value.parent();

其中var value = json.get("Cot");是对JSON对象中该值的引用,value.child();/value.parent();是对其相应子级/父级的引用。

注意:无论JSON的大小及其维度如何,这都必须有效。例如:

{
"val1" :  {
"val2" : {
"val3" : { 
"valX" 
}
}
}
}

以下是我在搜索其他人的作品后使用的内容:

function find(obj, item, value) {   
function objFind(obj, item, value){
for(var key in obj) {                                  
if(obj[key] && obj[key].length ==undefined) {     
if(obj[item]==value){
return obj;
}
objFind(obj[key], item, value);             

}else{ 
if(obj[key] && obj[key].length >0){
if(Array.isArray(obj[key])){
for(var i=0;i<obj[key].length;i++){
var results = objFind(obj[key][i], item, value);
if(typeof results === "object"){
return results;
}
}
}
}
}
}
}
if(obj.length >0){
for(var i=0;i<obj.length;i++){
var results=objFind(obj[i], item, value);
if(typeof results === "object"){
return results;
}
}
}
else{
var results=objFind(obj, item, value);
if(typeof results === "object"){
return results;
}
}
}

然后使用它:

var Target = find(jsonData,"id", 5);

最新更新