How to access the first property of a Javascript object?

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

提交回复
热议问题