[英]search for a key in json data using javascript
data:{
key1:{
child1:{},
child2:{}
}
key2:{
child21:{}
}
}
how can I get key2's child when i am not sure about key2's position?当我不确定 key2 的位置时,如何获得 key2 的孩子?
var keys = Object.keys(data);
This will return an array of strings of the key names.这将返回键名的字符串数组。 ["key1", "key2"]
I think specifically you need:我认为具体你需要:
var childnames = Object.keys(data[key2]);
You could turn this into an array of those objects that are it's children by:您可以通过以下方式将其转换为这些对象的数组,这些对象是它的子对象:
var key2children = [];
for(var i=0; i< childnames.length; i++){
key2children.push(data[key2][cildnames[i]);
}
EDIT Maybe this helps?:编辑也许这有帮助?:
//To get the children of an object
function getChildObjects(tgtobj){
var objchildren = [];
objectkeys = Object.keys(tgtobj);
for(var i=0; i< objectkeys.length; i++){
key2children.push(tgtobj[objectkeys[i]);
}
return objectchildren;
}
//This could be used to get the children of a child object in a function like this:
function getChildOjectsOfChildByName(tgtobj, name){
return getChildObjects(tgtobj[name]);
}
//usage example:
var key2childojects = getChildOjectsOfChildByName(data, "key2");
You would have to use a for in loop and recursion to get the nested key.您必须使用 for in 循环和递归来获取嵌套键。
function searchObj(obj, searVal){
for (ii in obj){
if(ii === searVal){
console.log(ii, ' -- my key');
} else{
console.log(ii, ' -- no key here');
searchObj(obj[ii], searVal);
}
}
}
searchObj(data, 'child21');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.