data:{
key1:{
child1:{},
child2:{}
}
key2:{
child21:{}
}
}
how can I get key2's child when i am not sure about key2's position?
data:{
key1:{
child1:{},
child2:{}
}
key2:{
child21:{}
}
}
how can I get key2's child when i am not sure about key2's position?
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.
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');