How to access the first property of a Javascript object?

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

    Here is a cleaner way of getting the first key:

    var object = {
        foo1: 'value of the first property "foo1"',
        foo2: { /* stuff2 */},
        foo3: { /* stuff3 */}
    };
    
    let [firstKey] = Object.keys(object)
    
    console.log(firstKey)
    console.log(object[firstKey])

提交回复
热议问题