获取 JavaScript 对象的所有键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4400035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:16:31  来源:igfitidea点击:

Get all keys of a JavaScript object

javascriptjqueryarraysjavascript-objects

提问by tishma

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).

我想知道是否有一种快速的方法可以使用 JavaScript(jQuery 可以)将关联数组的键提取到数组或逗号分隔列表中。

options = {key1: "value1", key2: "value2"};

Result should be the array:

结果应该是数组:

["key1", "key2"]

or just a string:

或者只是一个字符串:

"key1, key2"

回答by Nick Craver

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

您可以通过for循环轻松获取它们的数组,例如:

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

Then use keyshow you want, for example:

然后使用keys您想要的方式,例如:

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.

你可以在这里测试一下。该.hasOwnProperty()检查是为了安全起见,在与物体原型和这种混乱的情况下任何人。

回答by pwl

options = {key1: "value1", key2: "value2"};
keys = Object.keys(options);

回答by Ege ?zcan

A jQuery way of doing it:

一种 jQuery 方法:

var keys = [];
options = {key1: "value1", key2: "value2"};
$.each(options, function(key, value) { keys.push(key) })
console.log(keys)

回答by Andy E

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

现在大多数主流浏览器都内置了这个功能,方法是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:

该代码段与 Nick Craver 示例中的代码段非常相似,但有两个例外:

  • 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 hasOwnPropertymethod.
  • 如果您传入除 Object 之外的任何内容(或“关联数组”,如果您愿意),它会抛出一个有意义的 TypeError。
  • 它将解决 Internet Explorer 中令人讨厌的 DOM 相关问题,其中集合没有该hasOwnProperty方法。

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.

但是,这(以及此处的其他答案)并不能解决 IE 枚举错误。您可以在此处找到有关此答案的更多信息和部分解决方法。

回答by Ege ?zcan

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.

获取由对象中的可用键组成的数组。Mozilla 有使用和可用性信息

回答by Pointy

You can use $.each()in jQuery:

您可以$.each()在 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 jointo get a string.

给你["key1", "key2"]一个数组,你可以join得到一个字符串。