How to access the first property of a Javascript object?

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

    Use Object.keys to get an array of the properties on an object. Example:

    var example = {
        foo1: { /* stuff1 */},
        foo2: { /* stuff2 */},
        foo3: { /* stuff3 */}
    };
    
    var keys = Object.keys(example); // => ["foo1", "foo2", "foo3"] (Note: the order here is not reliable)
    

    Documentation and cross-browser shim provided here. An example of its use can be found in another one of my answers here.

    Edit: for clarity, I just want to echo what was correctly stated in other answers: the key order in javascript objects is undefined.

提交回复
热议问题