Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Getting all existing keys in a JSON array

I have a JSON array like below:

var jsonArray = [{"k1":"v1"},{"k2":"v2"},{"k3":"v3"},{"k4":"v4"},{"k5":"v5"}]

I don't know which keys does exists in this array. I want to get all the existing key from the array.

It should be possible something like this:

for(i=0;i<jsonArray.lenght;i++){
  // something like-  key = jsonArray[i].key
  // alert(key);
}

Please tell me the method or way to get all keys existing in Json array.

Regards

like image 474
S Singh Avatar asked Mar 19 '12 08:03

S Singh


People also ask

How do I get the key of a JSON object?

To get key and value from json object in javascript, you can use Object. keys() , Object. values() , for Object. entries() method the methods helps you to get both key and value from json object.

Can JSON have multiple keys?

No, you cannot. This is a limitation of JSON specification json.org You have to copy you values to each key from the array ["TypeA","TypeB","TypeC"] and store it separately.

Can JSON keys be arrays?

A JSON value can be an object, array, number, string, true, false, or null, and JSON structure can be nested up to any level.


2 Answers

Why don't you use a

var jsonObject = {"k1":"v1","k2":"v2","k3":"v3","k4":"v4","k5":"v5"}

instead of your

var jsonArray = [{"k1":"v1"},{"k2":"v2"},{"k3":"v3"},{"k4":"v4"},{"k5":"v5"}]

? Then the solution would be so simple: Object.keys(jsonObject).

like image 63
Bergi Avatar answered Sep 30 '22 21:09

Bergi


Try this:

var L = jsonArray.length;
for (var i = 0; i < L; i++) {
    var obj = jsonArray[i];
    for (var j in obj) {
        alert(j);
    }
}

I've also made some modifications of your current code (like length caching).

like image 21
freakish Avatar answered Sep 30 '22 20:09

freakish