Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving a property of a JSON object by index?

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.

like image 713
Šime Vidas Avatar asked Oct 28 '10 16:10

Šime Vidas


People also ask

How do you access the properties of an object in JSON?

To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.

How can I get the index from a JSON object?

To get the index from a JSON object with value with JavaScript, we can use the array findIndex method.

Can you index into a JSON?

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 .


1 Answers

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:

  • Iterating over a JavaScript object in sort order based on particular key value of a child object

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.

like image 128
Daniel Vassallo Avatar answered Sep 18 '22 17:09

Daniel Vassallo