Retrieving a property of a JSON object by index?

Viewed 188021

Assuming this JSON object:

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

The "set2" property may be retrieved like so:

obj["set2"]

Is there a way to retrieve the "set2" property by index? It is the second property of the JSON object. This does not work (of course):

obj[1]  

So, let's say that I want to retrieve the second property of the JSON object, but I don't know its name - how would I do it then?

Update: Yes, I understand that objects are collections of unordered properties. But I don't think that the browsers mess with the "original" order defined by the JSON literal / string.

12 Answers

it is quite simple...

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

jQuery.each(obj, function(i, val) {
 console.log(i); // "set1"
 console.log(val); // [1, 2, 3]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

var outputKeys = Object.keys(obj)[1];

var outputValues = Object.values(obj)[1];
//outputKeys would be "set2"`enter code here`
//outPutValues would be [4,5,6,7,8]
Related