Get all keys of a JavaScript object

2020-02-25 00:30发布

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"

6条回答
做个烂人
2楼-- · 2020-02-25 01:01

Most of the major browsers have this functionality built-in now, the method is Object.keys():

var keys = Object.keys(options);
//-> ["key1", "key2"]

You can also use a little snippet to implement this in browsers that don't support it:

Object.keys = Object.keys || (function () {
    var hasOwnProperty = Object.prototype.hasOwnProperty;

    return function (o) {
        if (typeof o != "object" && typeof o != "function" || o === null)
            throw new TypeError("Object.keys called on a non-object");

        var result = [];
        for (var name in o) {
            if (hasOwnProperty.call(o, name))
                result.push(name);
        }

        return result;
    };
})();

That snippet works much the same as the one in Nick Craver's example with 2 exceptions:

  • It will throw a meaningful TypeError if you pass anything other than an Object in (or "associative array", if you like).
  • It will work around an annoying DOM-related issue in Internet Explorer where collections don't have the hasOwnProperty method.

This (and the other answers here) doesn't work around an IE enumeration bug, however. You can find more information and a partial work around for that on this answer here.

查看更多
做个烂人
3楼-- · 2020-02-25 01:08

A jQuery way of doing it:

var keys = [];
options = {key1: "value1", key2: "value2"};
$.each(options, function(key, value) { keys.push(key) })
console.log(keys)
查看更多
小情绪 Triste *
4楼-- · 2020-02-25 01:09

You can use $.each() in jQuery:

function keyArray(obj) {
  var rv = [];
  $.each(options, function(key) { rv.push(key); });
  return rv;
}

then

var keys = keyArray(options);

gives you ["key1", "key2"] as an array, which you could join to get a string.

查看更多
我只想做你的唯一
5楼-- · 2020-02-25 01:11

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.

查看更多
做自己的国王
6楼-- · 2020-02-25 01:17

You can now use

Object.keys(obj)

to get an array consisting of the available keys in an object. Mozilla has usage and availability information.

查看更多
趁早两清
7楼-- · 2020-02-25 01:18
options = {key1: "value1", key2: "value2"};
keys = Object.keys(options);
查看更多
登录 后发表回答