Get index of a key in json

前端 未结 6 593
北恋
北恋 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: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
    });
    

提交回复
热议问题