Is there an elegant way to access the first property of an object...
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.
Any reason not to do this?
> example.map(x => x.name);
(3) ["foo1", "foo2", "foo3"]
if someone prefers array destructuring
const [firstKey] = Object.keys(object);
To get the first key name in the object you can use:
var obj = { first: 'someVal' };
Object.keys(obj)[0]; //returns 'first'
Returns a string, so you cant access nested objects if there were, like:
var obj = { first: { someVal : { id : 1} };
Here with that solution you can't access id.
The best solution if you want to get the actual object is using lodash like:
obj[_.first(_.keys(obj))].id
To return the value of the first key, (if you don't know exactly the first key name):
var obj = { first: 'someVal' };
obj[Object.keys(obj)[0]]; //returns 'someVal'
if you know the key name just use:
obj.first
or
obj['first']
You can use Object.prototype.keys
which returns all the keys of an object in the same order. So if you want the first object just get that array and use the first element as desired key.
const o = { "key1": "value1", "key2": "value2"};
const idx = 0; // add the index for which you want value
var key = Object.keys(o)[idx];
value = o[key]
console.log(key,value); // key2 value2
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.