Retrieving a property of a JSON object by index?

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

    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.

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

提交回复
热议问题