How to access the first property of a Javascript object?

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

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

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

    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.

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

    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.

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

    The top answer could generate the whole array and then capture from the list. Here is an another effective shortcut

    var obj = { first: 'someVal' };
    Object.entries(obj)[0][1] // someVal
    
    0 讨论(0)
  • 2020-11-22 09:45

    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.

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

    we can also do with this approch.

    var example = {
      foo1: { /* stuff1 */},
      foo2: { /* stuff2 */},
      foo3: { /* stuff3 */}
    }; 
    Object.entries(example)[0][1];
    
    0 讨论(0)
提交回复
热议问题