I have a json like so:
json = { \"key1\" : \"watevr1\", \"key2\" : \"watevr2\", \"key3\" : \"watevr3\" }
Now, I want to know the index of a key
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