Getting the first index of an object

2019-01-03 12:12发布

Consider:

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

How would I do this:

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

Obviously, that doesn’t work because the first index is named foo, not 0.

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

works, but I don’t know it’s named foo. It could be named anything. I just want the first.

14条回答
淡お忘
2楼-- · 2019-01-03 13:07

for first key of object you can use

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

for value

console.log(object[Object.keys(object)[0]]);//print key's value
查看更多
劳资没心,怎么记你
3楼-- · 2019-01-03 13:07

You could do something like this:

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'} )
查看更多
登录 后发表回答