Retrieving a property of a JSON object by index?

后端 未结 11 1008
情书的邮戳
情书的邮戳 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:33

    You could iterate over the object and assign properties to indexes, like this:

    var lookup = [];
    var i = 0;
    
    for (var name in obj) {
        if (obj.hasOwnProperty(name)) {
            lookup[i] = obj[name];
            i++;
        }
    }
    
    lookup[2] ...
    

    However, as the others have said, the keys are in principle unordered. If you have code which depends on the corder, consider it a hack. Make sure you have unit tests so that you will know when it breaks.

提交回复
热议问题