考虑:

var object = {
  foo: {},
  bar: {},
  baz: {}
}

我该怎么做:

var first = object[0];
console.log(first);

显然,这行不通,因为第一个索引名为foo, 不是0。

console.log(object['foo']);

工作,但我不知道它叫foo。它可以被命名为任何东西。我只想要第一个。


当前回答

对于对象的第一个键,您可以使用

console.log(Object.keys(object)[0]);//print key's name

价值

console.log(object[Object.keys(object)[0]]);//print key's value

其他回答

ES6

const [first] = Object.keys(obj)

你可以这样做:

var object = {
    foo:{a:'first'},
    bar:{},
    baz:{}
}


function getAttributeByIndex(obj, index){
  var i = 0;
  for (var attr in obj){
    if (index === i){
      return obj[attr];
    }
    i++;
  }
  return null;
}


var first = getAttributeByIndex(object, 0); // returns the value of the
                                            // first (0 index) attribute
                                            // of the object ( {a:'first'} )

我的解决方案:

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

对于对象的第一个键,您可以使用

console.log(Object.keys(object)[0]);//print key's name

价值

console.log(object[Object.keys(object)[0]]);//print key's value

获取对象的第一个键

const myObject = {
   'foo1': { name: 'myNam1' },
   'foo2': { name: 'myNam2' }
}

const result = Object.keys(myObject)[0];

// result will return 'foo1'