[javascript] 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.

This question is related to javascript json

The answer is


it is quite simple...

_x000D_
_x000D_
var obj = {_x000D_
    "set1": [1, 2, 3],_x000D_
    "set2": [4, 5, 6, 7, 8],_x000D_
    "set3": [9, 10, 11, 12]_x000D_
};_x000D_
_x000D_
jQuery.each(obj, function(i, val) {_x000D_
 console.log(i); // "set1"_x000D_
 console.log(val); // [1, 2, 3]_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_


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...
}

There is no "second property" -- when you say var obj = { ... }, the properties inside the braces are unordered. Even a 'for' loop walking through them might return them in different orders on different JavaScript implementations.


I know this is an old question but I found a way to get the fields by index. You can do it by using the Object.keys method.

When you call the Object.keys method it returns the keys in the order they were assigned (See the example below). I tested the method below in the following browsers:

  • Google Chrome version 43.0
  • Firefox version 33.1
  • Internet Explorer version 11

I also wrote a small extension to the object class so you can call the nth key of the object using getByIndex.

_x000D_
_x000D_
// Function to get the nth key from the object_x000D_
Object.prototype.getByIndex = function(index) {_x000D_
  return this[Object.keys(this)[index]];_x000D_
};_x000D_
_x000D_
var obj1 = {_x000D_
  "set1": [1, 2, 3],_x000D_
  "set2": [4, 5, 6, 7, 8],_x000D_
  "set3": [9, 10, 11, 12]_x000D_
};_x000D_
_x000D_
var obj2 = {_x000D_
  "set2": [4, 5, 6, 7, 8],_x000D_
  "set1": [1, 2, 3],_x000D_
  "set3": [9, 10, 11, 12]_x000D_
};_x000D_
_x000D_
log('-- Obj1 --');_x000D_
log(obj1);_x000D_
log(Object.keys(obj1));_x000D_
log(obj1.getByIndex(0));_x000D_
_x000D_
_x000D_
log('-- Obj2 --');_x000D_
log(obj2);_x000D_
log(Object.keys(obj2));_x000D_
log(obj2.getByIndex(0));_x000D_
_x000D_
_x000D_
// Log function to make the snippet possible_x000D_
function log(x) {_x000D_
  var d = document.createElement("div");_x000D_
  if (typeof x === "object") {_x000D_
    x = JSON.stringify(x, null, 4);_x000D_
  }_x000D_
  d.textContent= x;_x000D_
  document.body.appendChild(d);_x000D_
}
_x000D_
_x000D_
_x000D_


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.


Here you can access "set2" property following:

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

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

Object.keys return all the keys of provided object as Array..


"""
This could be done in python as follows.
Form the command as a string and then execute
"""
context = {
    "whoami": "abc",
    "status": "0",
    "curStep": 2,
    "parentStepStatus": {
        "step1":[{"stepStatus": 0, "stepLog": "f1.log"}],
        "step2":[{"stepStatus": 0, "stepLog": "f2.log"}]
    }
}
def punc():
          i = 1
          while (i < 10):
              x = "print(" + "context" + "['parentStepStatus']" + "['%s']"%("step%s")%(i) + ")"
              exec(x)
              i+=1
punc()

My solution:

Object.prototype.__index=function(index)
                         {var i=-1;
                          for (var key in this)
                              {if (this.hasOwnProperty(key) && typeof(this[key])!=='function')
                                  {++i;
                                  }
                               if (i>=index)
                                  {return this[key];
                                  }
                              }
                          return null;
                         }
aObj={'jack':3, 'peter':4, '5':'col', 'kk':function(){alert('hell');}, 'till':'ding'};
alert(aObj.__index(4));

Jeroen Vervaeke's answer is modular and the works fine, but it can cause problems if it is using with jQuery or other libraries that count on "object-as-hashtables" feature of Javascript.

I modified it a little to make usable with these libs.

function getByIndex(obj, index) {
  return obj[Object.keys(obj)[index]];
}

Simple solution, just one line..

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

obj = Object.values(obj);

obj[1]....