Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all keys of a JavaScript object

Tags:

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 = {key1: "value1", key2: "value2"};

Result should be the array:

["key1", "key2"]

or just a string:

"key1, key2"
like image 420
tishma Avatar asked Dec 09 '10 15:12

tishma


People also ask

How do you get all object keys?

The Object keys can be attained using the Object. keys() method. In JavaScript, the Object. keys() method returns an array containing all the object's own enumerable property names.

How do you iterate keys in JavaScript?

You have to pass the object you want to iterate, and the JavaScript Object. keys() method will return an array comprising all keys or property names. Then, you can iterate through that array and fetch the value of each property utilizing an array looping method such as the JavaScript forEach() loop.


1 Answers

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.

like image 128
Nick Craver Avatar answered Sep 19 '22 18:09

Nick Craver