考虑:
var object = {
foo: {},
bar: {},
baz: {}
}
我该怎么做:
var first = object[0];
console.log(first);
显然,这行不通,因为第一个索引名为foo, 不是0。
console.log(object['foo']);
工作,但我不知道它叫foo。它可以被命名为任何东西。我只想要第一个。
考虑:
var object = {
foo: {},
bar: {},
baz: {}
}
我该怎么做:
var first = object[0];
console.log(first);
显然,这行不通,因为第一个索引名为foo, 不是0。
console.log(object['foo']);
工作,但我不知道它叫foo。它可以被命名为任何东西。我只想要第一个。
当前回答
使用下划线时,可以使用_。将第一个对象条目作为键值对,如下所示:
_.pairs(obj)[0]
然后该键可以使用[0]下标,值为[1]
其他回答
ES6
const [first] = Object.keys(obj)
这不会给你第一个,因为javascript对象是无序的,但这在某些情况下是好的。
myObject[Object.keys(myObject)[0]]
你可以这样做:
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));
使用下划线时,可以使用_。将第一个对象条目作为键值对,如下所示:
_.pairs(obj)[0]
然后该键可以使用[0]下标,值为[1]