代码之家  ›  专栏  ›  技术社区  ›  Å ime Vidas Zim84

通过索引检索JSON对象的属性?

  •  36
  • Å ime Vidas Zim84  · 技术社区  · 14 年前

    假设这个JSON对象:

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

    obj["set2"]
    

    有没有办法通过索引检索“set2”属性?它是JSON对象的第二个属性。这不起作用(当然):

    obj[1]  
    

    所以,假设我想检索JSON对象的第二个属性,但是我不知道它的名称——那我该怎么做呢?

    更新:

    11 回复  |  直到 14 年前
        1
  •  30
  •   Community datashaman    7 年前

    JavaScript中的对象是 无序的

    如果希望属性按字母顺序排列,一种可能的解决方案是在单独的数组中为属性创建索引。就在几个小时前,我回答了一个关于堆栈溢出的问题,您可能想查看一下:

    这里有一个快速适应你的对象 1个

    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); 
    }); 
    

    然后您可以执行以下操作:

    console.log(obj[index[1]]);
    

    这个 answer I cited 前面提出了一个可重用的解决方案来遍历这样的对象。除非您可以将JSON更改为 @Jacob Relkin suggested in the other answer


    1个 hasOwnProperty() 方法以确保属性属于您的对象且不从中继承 Object.prototype .

        2
  •  19
  •   Jacob Relkin    14 年前

    如果您有权访问这个JSON的源代码,一个解决方案是将每个元素更改为一个JSON对象,并将键插入该对象,如下所示:

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

    然后,您将能够以数字方式访问元素:

    for(var i = 0; i < obj.length; i++) {
        var k = obj[i]['key'];
        var data = obj[i]['data'];
        //do something with k or data...
    }
    
        3
  •  18
  •   Jeroen Vervaeke    9 年前

    您可以使用 Object.keys 方法。

    对象.keys 方法按键的分配顺序返回键(参见下面的示例)。我在以下浏览器中测试了以下方法:

    • 谷歌Chrome 43.0版
    • Internet Explorer版本11

    我还为object类编写了一个小扩展,这样您就可以使用 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);
    }
        4
  •  8
  •   Vishant dhandha    9 年前

    在这里您可以访问“set2”属性:

        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以数组的形式返回所提供对象的所有键。。

        5
  •  5
  •   Faris Mohammed    7 年前

    简单的解决方案,只有一行。。

    var obj = {
        "set1": [1, 2, 3],
        "set2": [4, 5, 6, 7, 8],
        "set3": [9, 10, 11, 12]
    };
    
    obj = Object.values(obj);
    
    obj[1]....
    
        6
  •  3
  •   Douglas    14 年前

    您可以迭代对象并将属性分配给索引,如下所示:

    var lookup = [];
    var i = 0;
    
    for (var name in obj) {
        if (obj.hasOwnProperty(name)) {
            lookup[i] = obj[name];
            i++;
        }
    }
    
    lookup[2] ...
    

        7
  •  3
  •   Gagik Sargsyan    7 年前

    Jeroen Vervaeke 的答案是模块化的,工作正常,但是 can cause problems 如果它与jQuery或其他依赖于Javascript的“object as hashtables”特性的库一起使用。

    function getByIndex(obj, index) {
      return obj[Object.keys(obj)[index]];
    }
    
        8
  •  1
  •   raccoon    7 年前
    """
    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()
    
        9
  •  0
  •   Mike Morearty NiCk Newman    14 年前

    没有“第二财产”——当你说 var obj = { ... } ,大括号中的属性是无序的。即使是遍历它们的“for”循环,也可能在不同的JavaScript实现上以不同的顺序返回它们。

        10
  •  0
  •   Anas Abu Farraj Csaba K.    5 年前

    很简单。。。

    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>
        11
  •  -1
  •   diyism    13 年前

    我的解决方案:

    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));