How to access the first property of a Javascript object?

前端 未结 19 2398
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 09:00

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
相关标签:
19条回答
  • 2020-11-22 09:24
    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.

    0 讨论(0)
  • 2020-11-22 09:24

    Any reason not to do this?

    > example.map(x => x.name);
    
    (3) ["foo1", "foo2", "foo3"]
    
    0 讨论(0)
  • 2020-11-22 09:25

    if someone prefers array destructuring

    const [firstKey] = Object.keys(object);
    
    0 讨论(0)
  • 2020-11-22 09:26

    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']
    
    0 讨论(0)
  • 2020-11-22 09:29

    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
    
    0 讨论(0)
  • 2020-11-22 09:33

    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.

    0 讨论(0)
提交回复
热议问题