[javascript] Get index of a key in json

I have a json like so:

json = { "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" }

Now, I want to know the index of a key, say "key2" in json - which is 1. Is there a way?

This question is related to javascript json

The answer is


You don't need a numerical index for an object key, but many others have told you that.

Here's the actual answer:

var json = { "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" };

console.log( getObjectKeyIndex(json, 'key2') ); 
// Returns int(1) (or null if the key doesn't exist)

function getObjectKeyIndex(obj, keyToFind) {
    var i = 0, key;

    for (key in obj) {
        if (key == keyToFind) {
            return i;
        }

        i++;
    }

    return null;
}

Though you're PROBABLY just searching for the same loop that I've used in this function, so you can go through the object:

for (var key in json) {
    console.log(key + ' is ' + json[key]);
}

Which will output

key1 is watevr1
key2 is watevr2
key3 is watevr3

What you have is a string representing a JSON serialized javascript object. You need to deserialize it back a javascript object before being able to loop through its properties. Otherwise you will be looping through each individual character of this string.

var resultJSON = '{ "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" }';
    var result = $.parseJSON(resultJSON);
    $.each(result, function(k, v) {
        //display the key and value pair
        alert(k + ' is ' + v);
    });

or simply:

arr.forEach(function (val, index, theArray) {
    //do stuff
});

In principle, it is wrong to look for an index of a key. Keys of a hash map are unordered, you should never expect specific order.


Try this

var json = '{ "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" }';
json = $.parseJSON(json);

var i = 0, req_index = "";
$.each(json, function(index, value){
    if(index == 'key2'){
        req_index = i;
    }
    i++;
});
alert(req_index);

What you are after are numerical indexes in the way classic arrays work, however there is no such thing with json object/associative arrays.

"key1", "key2" themeselves are the indexes and there is no numerical index associated with them. If you want to have such functionality you have to assiciate them yourself.