How to access the first property of an object in J

2019-01-01 14:08发布

Is there an elegant way to access the first property of an object...

  1. where you don't know the name of your properties
  2. without using a loop like for .. in or jQuery's $.each

For example, I need to access foo1 object without knowing the name of foo1:

var example = {
    foo1: { /* stuff1 */},
    foo2: { /* stuff2 */},
    foo3: { /* stuff3 */}
};

13条回答
忆尘夕之涩
2楼-- · 2019-01-01 14:33
var obj = { first: 'someVal' };
obj[Object.keys(obj)[0]]; //returns 'someVal'

Using this you can access also other properties by indexes. Be aware tho! Object.keys return order is not guaranteed as per ECMAScript however unofficially it is by all major browsers implementations, please read https://stackoverflow.com/a/23202095 for details on this.

查看更多
墨雨无痕
3楼-- · 2019-01-01 14:33

A one-rule version:

var val = example[function() { for (var k in example) return k }()];
查看更多
听够珍惜
4楼-- · 2019-01-01 14:34

If you need to access "the first property of an object", it might mean that there is something wrong with your logic. The order of an object's properties should not matter.

查看更多
妖精总统
5楼-- · 2019-01-01 14:36

This has been covered here before.

The concept of first does not apply to object properties, and the order of a for...in loop is not guaranteed by the specs, however in practice it is reliably FIFO except critically for chrome (bug report). Make your decisions accordingly.

查看更多
ら面具成の殇う
6楼-- · 2019-01-01 14:38

Use Object.keys to get an array of the properties on an object. Example:

var example = {
    foo1: { /* stuff1 */},
    foo2: { /* stuff2 */},
    foo3: { /* stuff3 */}
};

var keys = Object.keys(example); // => ["foo1", "foo2", "foo3"] (Note: the order here is not reliable)

Documentation and cross-browser shim provided here. An example of its use can be found in another one of my answers here.

Edit: for clarity, I just want to echo what was correctly stated in other answers: the key order in javascript objects is undefined.

查看更多
栀子花@的思念
7楼-- · 2019-01-01 14:39

Try the for … in loop and break after the first iteration:

for (var prop in object) {
    // object[prop]
    break;
}
查看更多
登录 后发表回答