-4
data:{
key1:{
   child1:{},
   child2:{}
 }
key2:{
  child21:{}
 }
}

how can I get key2's child when i am not sure about key2's position?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 4
    it's an object, just use the key. – Nina Scholz Jan 05 '17 at 19:59
  • 2
    `data.key2.child21`...or `data["key2"]["child21"]` you can use variables if you don't know the key at design time. – brso05 Jan 05 '17 at 19:59
  • 2
    What do you mean by position? –  Jan 05 '17 at 20:00
  • I want ot list all the children of given parent and in this case the given parent is key2. – user3738874 Jan 05 '17 at 20:01
  • Well when speaking of JSON data you'd first have to parse it.... then get the value by key. – trincot Jan 05 '17 at 20:01
  • 1
    Please provide the literal result you want to have for some sample data. You want output "child21", or "{}", or still something else? – trincot Jan 05 '17 at 20:04
  • 2
    To @ProfessorAllman's point, there is no "position" in objects. There are only keys. The order is not determined, and should not be considered fixed. (See http://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order) – alttag Jan 05 '17 at 20:04
  • 1
    What you posted is not JSON. Please read the [tag:json] tag description: *"Use this tag when this text format is involved, but not for native JavaScript objects."* It seems you are talking about JavaScript objects. – Felix Kling Jan 05 '17 at 20:06
  • Also, this should help: [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/q/11922383/218196) – Felix Kling Jan 05 '17 at 20:08

2 Answers2

0
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");
Grallen
  • 1,620
  • 1
  • 17
  • 16
0

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');
andre mcgruder
  • 1,120
  • 1
  • 9
  • 12