Get index of a key in json

前端 未结 6 540
北恋
北恋 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条回答
  • 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
    
    0 讨论(0)
  • 2021-01-31 04:27

    Its too late, but it may be simple and useful

    var json = { "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" };
    var keytoFind = "key2";
    var index = Object.keys(json).indexOf(keytoFind);
    alert(index);
    
    0 讨论(0)
  • 2021-01-31 04:31

    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
    });
    
    0 讨论(0)
  • 2021-01-31 04:35

    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.

    0 讨论(0)
  • 2021-01-31 04:44

    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);
    
    0 讨论(0)
  • 2021-01-31 04:50

    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.

    0 讨论(0)
提交回复
热议问题