Retrieving a property of a JSON object by index?

后端 未结 11 1007
情书的邮戳
情书的邮戳 2020-12-02 13:28

Assuming this JSON object:

var obj = {
    \"set1\": [1, 2, 3],
    \"set2\": [4, 5, 6, 7, 8],
    \"set3\": [9, 10, 11, 12]
};

The \"set

11条回答
  •  醉话见心
    2020-12-02 13:56

    No, there is no way to access the element by index in JavaScript objects.

    One solution to this if you have access to the source of this JSON, would be to change each element to a JSON object and stick the key inside of that object like this:

    var obj = [
        {"key":"set1", "data":[1, 2, 3]},
        {"key":"set2", "data":[4, 5, 6, 7, 8]},
        {"key":"set3", "data":[9, 10, 11, 12]}
    ];
    

    You would then be able to access the elements numerically:

    for(var i = 0; i < obj.length; i++) {
        var k = obj[i]['key'];
        var data = obj[i]['data'];
        //do something with k or data...
    }
    

提交回复
热议问题