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:40

There isn't a "first" property. Object keys are unordered.

If you loop over them with for (var foo in bar) you will get them in some order, but it may change in future (especially if you add or remove other keys).

查看更多
不流泪的眼
3楼-- · 2019-01-01 14:41

Solution with lodash library:

_.find(example) // => {name: "foo1"}

but there is no guarantee of the object properties internal storage order because it depends on javascript VM implementation.

查看更多
人气声优
4楼-- · 2019-01-01 14:51

You can also do Object.values(example)[0].

查看更多
谁念西风独自凉
5楼-- · 2019-01-01 14:51

Any reason not to do this?

> example.map(x => x.name);

(3) ["foo1", "foo2", "foo3"]
查看更多
与君花间醉酒
6楼-- · 2019-01-01 14:53

No. An object literal, as defined by MDC is:

a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}).

Therefore an object literal is not an array, and you can only access the properties using their explicit name or a for loop using the in keyword.

查看更多
初与友歌
7楼-- · 2019-01-01 14:54

Use an array instead of an object (square brackets).

var example = [ {/* stuff1 */}, { /* stuff2 */}, { /* stuff3 */}];
var fist = example[0];

Note that you lose the 'foo' identifiers. But you could add a name property to the contained objects:

var example = [ 
  {name: 'foo1', /* stuff1 */},
  {name: 'foo2', /* stuff2 */},
  {name: 'foo3', /* stuff3 */}
];
var whatWasFirst = example[0].name;
查看更多
登录 后发表回答