Get index of a key in json

前端 未结 6 545
北恋
北恋 2021-01-31 03:48

I have a json like so:

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

Now, I want to know the index of a key

6条回答
  •  梦毁少年i
    2021-01-31 04:26

    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
    

提交回复
热议问题