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.
To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.
To get the index from a JSON object with value with JavaScript, we can use the array findIndex method.
You can index JSON data as you would any data of the type that you use to store it. In particular, you can use a B-tree index or a bitmap index for SQL/JSON function json_value , and you can use a bitmap index for SQL/JSON conditions is json , is not json , and json_exists .
Objects in JavaScript are collections of unordered properties. Objects are hashtables.
If you want your properties to be in alphabetical order, one possible solution would be to create an index for your properties in a separate array. Just a few hours ago, I answered a question on Stack Overflow which you may want to check out:
Here's a quick adaptation for your object1:
var obj = { "set1": [1, 2, 3], "set2": [4, 5, 6, 7, 8], "set3": [9, 10, 11, 12] }; var index = []; // build the index for (var x in obj) { index.push(x); } // sort the index index.sort(function (a, b) { return a == b ? 0 : (a > b ? 1 : -1); });
Then you would be able to do the following:
console.log(obj[index[1]]);
The answer I cited earlier proposes a reusable solution to iterate over such an object. That is unless you can change your JSON to as @Jacob Relkin suggested in the other answer, which could be easier.
1 You may want to use the hasOwnProperty()
method to ensure that the properties belong to your object and are not inherited from Object.prototype
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With