Get all keys of a JavaScript object

前端 未结 6 2186
遇见更好的自我
遇见更好的自我 2020-12-30 03:59

I was wondering if there was a quick way to extract keys of associative array into an array, or comma-separated list using JavaScript (jQuery is ok).

options         


        
6条回答
  •  抹茶落季
    2020-12-30 03:59

    You can easily get an array of them via a for loop, for example:

    var keys = [];
    for(var key in options) {
      if(options.hasOwnProperty(key)) { //to be safe
        keys.push(key);
      }
    }
    

    Then use keys how you want, for example:

    var keyString = keys.join(", ");
    

    You can test it out here. The .hasOwnProperty() check is to be safe, in case anyone messed with the object prototype and such.

提交回复
热议问题