Accessing elements of JSON object without knowing the key names

94,782

Solution 1

You can use the for..in construct to iterate through arbitrary properties of your object:

for (var key in obj.d) {
    console.log("Key: " + key);
    console.log("Value: " + obj.d[key]);
}

Solution 2

Is this what you're looking for?

var data;
for (var key in data) {
   var value = data[key];
   alert(key + ", " + value);
}

Solution 3

{
  "d":{
     "key1":"value1",
     "key2":"value2"
    }
}

To access first key write:

   let firstKey=Object.keys(d)[0];

To access value of first key write:

let firstValue= d[firstKey];

Solution 4

Use for loop to achieve the same.

var dlist = { country: [ 'ENGLAND' ], name: [ 'CROSBY' ] }

for(var key in dlist){
     var keyjson = dlist[key];
     console.log(keyjson)
   }

Solution 5

By using word "b", You are still using key name.

var info = {
"fname": "Bhaumik",
"lname": "Mehta",
"Age": "34",
"favcolor": {"color1":"Gray", "color2":"Black", "color3":"Blue"}
};

Look at the below snippet.

for(key in info) {
  var infoJSON = info[key];
  console.log(infoJSON);
}

Result would be,

Bhaumik
Mehta
Object {color1: "Gray", color2: "Black", color3: "Blue"} 

Don’t want that last line to show up? Try following code:

for(key in info) {
  var infoJSON = info[key];
    if(typeof infoJSON !== "object"){
       console.log(infoJSON);
  }
}

This will eliminate Object {color1: “Gray”, color2: “Black”, color3: “Blue”} from showing up in the console.

Now we need to iterate through the variable infoJSON to get array value. Look at the following whole peace of code.

for(key in info) {
    var infoJSON = info[key];
    if (typeof infoJSON !== "object"){
       console.log(infoJSON);
    }
 }

for(key1 in infoJSON) {
    if (infoJSON.hasOwnProperty(key1)) {
       if(infoJSON[key1] instanceof Array) {
          for(var i=0;i<infoJSON[key1].length;i++) {
             console.log(infoJSON[key1][i]);
          }
        } else {console.log(infoJSON[key1]);}
    }
 }

And now we got the result as

Bhaumik
Mehta
Gray
Black
Blue

If we use key name or id then it’s very easy to get the values from the JSON object but here we are getting our values without using key name or id.

Share:
94,782
Radu
Author by

Radu

Updated on March 31, 2020

Comments

  • Radu
    Radu about 4 years

    Here's my json:

    {"d":{"key1":"value1",
          "key2":"value2"}}
    

    Is there any way of accessing the keys and values (in javascript) in this array without knowing what the keys are?

    The reason my json is structured like this is that the webmethod that I'm calling via jquery is returning a dictionary. If it's impossible to work with the above, what do I need to change about the way I'm returning the data?

    Here's an outline of my webmethod:

    <WebMethod()> _
    Public Function Foo(ByVal Input As String) As Dictionary(Of String, String)
        Dim Results As New Dictionary(Of String, String)
    
        'code that does stuff
    
        Results.Add(key,value)
        Return Results
    End Function
    
  • Ates Goral
    Ates Goral about 13 years
    Tip: Don't call JavaScript objects JSON objects. JSON is the transport format. Once parsed, there's no JSON.
  • Ates Goral
    Ates Goral about 13 years
    Tip2: A more concise way to alert multiple values: alert([key, value])
  • Xenethyl
    Xenethyl about 13 years
    @Ates Goral My implication with the var name was that it contained the JSON data, not that it was a JSON object. Poor choice, I suppose.
  • Radu
    Radu about 13 years
    Perfect. Do I still need to use a for in if there is only one key value pair?
  • Xenethyl
    Xenethyl about 13 years
    @Radu You can't access the properties of an object with indices, so you will need to get the key(s) using a for...in.
  • Radu
    Radu about 13 years
    Thanks. Accepted the other answer as it was slightly better tuned to my json data.
  • Xenethyl
    Xenethyl about 13 years
    @Radu You're welcome, and no problem. Glad we were able to help you.
  • David
    David about 12 years
    What if the JSON has a list of objects and you want to get the object names? Like {"d":{"key1":"value1","key2":"value2"},"e":{"key1":"value1",‌​"key2":"value2"}} and you want name of d and e, but you don't know they're called d and e at runtime.
  • Ates Goral
    Ates Goral about 12 years
    The "key" variable in the top-level iteration would give you the "object names".
  • cackharot
    cackharot almost 10 years
    You might need to use obj.d.hasOwnProperty(key) inside for block to get rid of the inner private properties.
  • Akah
    Akah about 7 years
    This has saved me over 6 hours of searching. Works well with deep children in firebase tree.