How to access the first property of a Javascript object?

前端 未结 19 2727
爱一瞬间的悲伤
爱一瞬间的悲伤 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: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']
    

提交回复
热议问题