如何列出JavaScript对象的属性?

时间:2022-08-30 10:14:27

Say I create an object thus:

假设我创建一个对象:

var myObject =
        {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};

What is the best way to retrieve a list of the property names? i.e. I would like to end up with some variable 'keys' such that:

检索属性名列表的最佳方法是什么?也就是说,我想用一些变量“键”来表示:

keys == ["ircEvent", "method", "regex"]

16 个解决方案

#1


876  

In modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) you can use the built in Object.keys method:

在现代浏览器中(IE9+、FF4+、Chrome5+、Opera12+、Safari5+),可以使用内置对象。键的方法:

var keys = Object.keys(myObject);

The above has a full polyfill but a simplified version is:

上面有一个完整的polyfill,但一个简化的版本是:

var getKeys = function(obj){
   var keys = [];
   for(var key in obj){
      keys.push(key);
   }
   return keys;
}

Alternatively replace var getKeys with Object.prototype.keys to allow you to call .keys() on any object. Extending the prototype has some side effects and I wouldn't recommend doing it.

或者用Object.prototype替换var getKeys。允许您在任何对象上调用.keys()的键。扩展原型有一些副作用,我不建议这么做。

#2


232  

As slashnick pointed out, you can use the "for in" construct to iterate over an object for its attribute names. However you'll be iterating over all attribute names in the object's prototype chain. If you want to iterate only over the object's own attributes, you can make use of the Object#hasOwnProperty() method. Thus having the following.

正如slashnick所指出的那样,您可以使用“for in”构造来遍历对象的属性名称。不过,您将遍历对象的原型链中的所有属性名称。如果您只想遍历对象本身的属性,则可以使用对象#hasOwnProperty()方法。因此有以下。

for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        /* useful code here */
    }
}

#3


96  

As Sam Dutton answered, a new method for this very purpose has been introduced in ECMAScript 5th Edition. Object.keys() will do what you want and is supported in Firefox 4, Chrome 6, Safari 5 and IE 9.

正如Sam Dutton所回答的,在ECMAScript第5版中引入了一种新的方法。Object.keys()会做你想做的事情,并在Firefox 4、Chrome 6、Safari 5和ie9中得到支持。

You can also very easily implement the method in browsers that don't support it. However, some of the implementations out there aren't fully compatible with Internet Explorer. I've detailed this on my blog and produced a more compatible solution:

您还可以很容易地在不支持它的浏览器中实现该方法。然而,有些实现并不完全兼容Internet Explorer。我在博客上详细说明了这一点,并提出了一个更兼容的解决方案:

Object.keys = Object.keys || (function () {
    var hasOwnProperty = Object.prototype.hasOwnProperty,
        hasDontEnumBug = !{toString:null}.propertyIsEnumerable("toString"),
        DontEnums = [ 
            'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty',
            'isPrototypeOf', 'propertyIsEnumerable', 'constructor'
        ],
        DontEnumsLength = DontEnums.length;

    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);
        }

        if (hasDontEnumBug) {
            for (var i = 0; i < DontEnumsLength; i++) {
                if (hasOwnProperty.call(o, DontEnums[i]))
                    result.push(DontEnums[i]);
            }   
        }

        return result;
    };
})();

Note that the currently accepted answer doesn't include a check for hasOwnProperty() and will return properties that are inherited through the prototype chain. It also doesn't account for the famous DontEnum bug in Internet Explorer where non-enumerable properties on the prototype chain cause locally declared properties with the same name to inherit their DontEnum attribute.

注意,当前接受的答案不包括对hasOwnProperty()的检查,并且将返回通过原型链继承的属性。它也不能解释Internet Explorer中著名的DontEnum bug,因为原型链上的不可数属性导致本地声明的属性具有相同的名称,从而继承他们的DontEnum属性。

Implementing Object.keys() will give you a more robust solution.

实现Object.keys()将给您一个更健壮的解决方案。

EDIT: following a recent discussion with kangax, a well-known contributor to Prototype, I implemented the workaround for the DontEnum bug based on code for his Object.forIn() function found here.

编辑:在最近与一个著名的原型开发人员kangax的讨论之后,我基于他的Object.forIn()函数的代码实现了DontEnum bug的工作。

#4


27  

Note that Object.keys and other ECMAScript 5 methods are supported by Firefox 4, Chrome 6, Safari 5, IE 9 and above.

注意,对象。密钥和其他ECMAScript 5方法得到了Firefox 4、Chrome 6、Safari 5、ie9和以上的支持。

For example:

例如:

var o = {"foo": 1, "bar": 2}; 
alert(Object.keys(o));

ECMAScript 5 compatibility table: http://kangax.github.com/es5-compat-table/

ECMAScript 5兼容表:http://kangax.github.com/es5-compat-table/。

Description of new methods: http://markcaudill.com/index.php/2009/04/javascript-new-features-ecma5/

新方法的描述:http://markcaudill.com/index.php/2009/04/javascript-new features-ecma5/。

#5


15  

I'm a huge fan of the dump function.

我是转储函数的超级粉丝。

http://ajaxian.com/archives/javascript-variable-dump-in-coldfusion 如何列出JavaScript对象的属性?

http://ajaxian.com/archives/javascript-variable-dump-in-coldfusion

#6


14  

Object.getOwnPropertyNames(obj)

Object.getOwnPropertyNames(obj)

This function also shows non-enumerable properties in addition to those shown by Object.keys(obj).

除了Object.keys(obj)之外,该函数还显示了不可枚举的属性。

In JS, every property has a few properties, including a boolean enumerable.

在JS中,每个属性都有一些属性,包括布尔枚举。

In general, non-enumerable properties are more "internalish" and less often used, but it is insightful to look into them sometimes to see what is really going on.

一般来说,不可枚举的属性更像“internalish”,而不是经常使用,但是有时候查看它们是很有见地的,看看到底发生了什么。

Example:

例子:

var o = Object.create({base:0})
Object.defineProperty(o, 'yes', {enumerable: true})
Object.defineProperty(o, 'not', {enumerable: false})

console.log(Object.getOwnPropertyNames(o))
// [ 'yes', 'not' ]

console.log(Object.keys(o))
// [ 'yes' ]

for (var x in o)
    console.log(x)
// yes, base

Also note how:

还请注意:

  • Object.getOwnPropertyNames and Object.keys don't go up the prototype chain to find base
  • 对象。getOwnPropertyNames和对象。钥匙不上原型链去寻找基地。
  • for in does
  • 因为在做

More about the prototype chain here: https://*.com/a/23877420/895245

关于原型链的更多信息:https://*.com/a/23877420/895245。

#7


13  

Could do it with jQuery as follows:

可以使用jQuery进行如下操作:

var objectKeys = $.map(object, function(value, key) {
  return key;
});

#8


8  

if you are trying to get the elements only but not the functions then this code can help you

如果您试图仅获取元素而不是函数,那么这段代码可以帮助您。

this.getKeys = function() {

    var keys = new Array();
    for(var key in this) {

        if( typeof this[key] !== 'function') {

            keys.push(key);
        }
    }
    return keys;
}

this is part of my implementation of the HashMap and I only want the keys, "this" is the hashmap object that contains the keys

这是我的HashMap实现的一部分,我只需要键,“this”是包含键的HashMap对象。

#9


7  

This will work in most browsers, even in IE8 , and no libraries of any sort are required. var i is your key.

这将在大多数浏览器中工作,即使在IE8中,也不需要任何类型的库。我是你的钥匙。

var myJSONObject =  {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"}; 
var keys=[];
for (var i in myJSONObject ) { keys.push(i); }
alert(keys);

#10


6  

Under browsers supporting js 1.8:

浏览器支持js 1.8:

[i for(i in obj)]

#11


5  

Mozilla has full implementation details on how to do it in a browser where it isn't supported, if that helps:

Mozilla有完整的实现细节,关于如何在不支持它的浏览器中实现它,如果有帮助的话:

if (!Object.keys) {
  Object.keys = (function () {
    var hasOwnProperty = Object.prototype.hasOwnProperty,
        hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
        dontEnums = [
          'toString',
          'toLocaleString',
          'valueOf',
          'hasOwnProperty',
          'isPrototypeOf',
          'propertyIsEnumerable',
          'constructor'
        ],
        dontEnumsLength = dontEnums.length;

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

      var result = [];

      for (var prop in obj) {
        if (hasOwnProperty.call(obj, prop)) result.push(prop);
      }

      if (hasDontEnumBug) {
        for (var i=0; i < dontEnumsLength; i++) {
          if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
        }
      }
      return result;
    };
  })();
}

You could include it however you'd like, but possibly in some kind of extensions.js file at the top of your script stack.

你可以把它包括在你想要的地方,但可能是在某种扩展中。js文件位于脚本堆栈的顶部。

#12


3  

IE does not support for(i in obj) for native properties. Here is a list of all the props I could find.

IE不支持本机属性(我在obj中)。这是我能找到的所有道具的清单。

It seems * does some stupid filtering.

看起来*做了一些愚蠢的过滤。

The list is available at the bottom of this google group post:- https://groups.google.com/group/hackvertor/browse_thread/thread/a9ba81ca642a63e0

该列表在谷歌组的底部可用:- https://groups.google.com/group/hackvertor/browse_thread/a9ba81ca642a63e0。

#13


3  

Since I use underscore.js in almost every project, I would use the keys function:

因为我使用下划线。在几乎每个项目中,我都会使用键函数:

var obj = {name: 'gach', hello: 'world'};
console.log(_.keys(obj));

The output of that will be:

其输出将是:

['name', 'hello']

#14


1  

Building on the accepted answer.

建立在公认的答案上。

If the Object has properties you want to call say .properties() try!

如果对象有属性,您需要调用。properties()尝试!

var keys = Object.keys(myJSONObject);

for (j=0; j < keys.length; j++) {
  Object[keys[i]].properties();
}

#15


0  

The solution work on my cases and cross-browser:

解决方案在我的案例和跨浏览器:

var getKeys = function(obj) {
    var type = typeof  obj;
    var isObjectType = type === 'function' || type === 'object' || !!obj;

    // 1
    if(isObjectType) {
        return Object.keys(obj);
    }

    // 2
    var keys = [];
    for(var i in obj) {
        if(obj.hasOwnProperty(i)) {
            keys.push(i)
        }
    }
    if(keys.length) {
        return keys;
    }

    // 3 - bug for ie9 <
    var hasEnumbug = !{toString: null}.propertyIsEnumerable('toString');
    if(hasEnumbug) {
        var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
            'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];

        var nonEnumIdx = nonEnumerableProps.length;

        while (nonEnumIdx--) {
            var prop = nonEnumerableProps[nonEnumIdx];
            if (Object.prototype.hasOwnProperty.call(obj, prop)) {
                keys.push(prop);
            }
        }

    }

    return keys;
};

#16


0  

You can use an object-values reusable component to get all of the object's values.

您可以使用对象值可重用组件来获取所有对象的值。

Example:

例子:

values({ a: 1, b: 2, c: 3 }) // => [1, 2, 3]

How it works:

它是如何工作的:

function values(object: {[any]: any}): any[] {
  const objValues = [];
  forEach(object, val => objValues.push(val)); 
  return objValues;
};

#1


876  

In modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) you can use the built in Object.keys method:

在现代浏览器中(IE9+、FF4+、Chrome5+、Opera12+、Safari5+),可以使用内置对象。键的方法:

var keys = Object.keys(myObject);

The above has a full polyfill but a simplified version is:

上面有一个完整的polyfill,但一个简化的版本是:

var getKeys = function(obj){
   var keys = [];
   for(var key in obj){
      keys.push(key);
   }
   return keys;
}

Alternatively replace var getKeys with Object.prototype.keys to allow you to call .keys() on any object. Extending the prototype has some side effects and I wouldn't recommend doing it.

或者用Object.prototype替换var getKeys。允许您在任何对象上调用.keys()的键。扩展原型有一些副作用,我不建议这么做。

#2


232  

As slashnick pointed out, you can use the "for in" construct to iterate over an object for its attribute names. However you'll be iterating over all attribute names in the object's prototype chain. If you want to iterate only over the object's own attributes, you can make use of the Object#hasOwnProperty() method. Thus having the following.

正如slashnick所指出的那样,您可以使用“for in”构造来遍历对象的属性名称。不过,您将遍历对象的原型链中的所有属性名称。如果您只想遍历对象本身的属性,则可以使用对象#hasOwnProperty()方法。因此有以下。

for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        /* useful code here */
    }
}

#3


96  

As Sam Dutton answered, a new method for this very purpose has been introduced in ECMAScript 5th Edition. Object.keys() will do what you want and is supported in Firefox 4, Chrome 6, Safari 5 and IE 9.

正如Sam Dutton所回答的,在ECMAScript第5版中引入了一种新的方法。Object.keys()会做你想做的事情,并在Firefox 4、Chrome 6、Safari 5和ie9中得到支持。

You can also very easily implement the method in browsers that don't support it. However, some of the implementations out there aren't fully compatible with Internet Explorer. I've detailed this on my blog and produced a more compatible solution:

您还可以很容易地在不支持它的浏览器中实现该方法。然而,有些实现并不完全兼容Internet Explorer。我在博客上详细说明了这一点,并提出了一个更兼容的解决方案:

Object.keys = Object.keys || (function () {
    var hasOwnProperty = Object.prototype.hasOwnProperty,
        hasDontEnumBug = !{toString:null}.propertyIsEnumerable("toString"),
        DontEnums = [ 
            'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty',
            'isPrototypeOf', 'propertyIsEnumerable', 'constructor'
        ],
        DontEnumsLength = DontEnums.length;

    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);
        }

        if (hasDontEnumBug) {
            for (var i = 0; i < DontEnumsLength; i++) {
                if (hasOwnProperty.call(o, DontEnums[i]))
                    result.push(DontEnums[i]);
            }   
        }

        return result;
    };
})();

Note that the currently accepted answer doesn't include a check for hasOwnProperty() and will return properties that are inherited through the prototype chain. It also doesn't account for the famous DontEnum bug in Internet Explorer where non-enumerable properties on the prototype chain cause locally declared properties with the same name to inherit their DontEnum attribute.

注意,当前接受的答案不包括对hasOwnProperty()的检查,并且将返回通过原型链继承的属性。它也不能解释Internet Explorer中著名的DontEnum bug,因为原型链上的不可数属性导致本地声明的属性具有相同的名称,从而继承他们的DontEnum属性。

Implementing Object.keys() will give you a more robust solution.

实现Object.keys()将给您一个更健壮的解决方案。

EDIT: following a recent discussion with kangax, a well-known contributor to Prototype, I implemented the workaround for the DontEnum bug based on code for his Object.forIn() function found here.

编辑:在最近与一个著名的原型开发人员kangax的讨论之后,我基于他的Object.forIn()函数的代码实现了DontEnum bug的工作。

#4


27  

Note that Object.keys and other ECMAScript 5 methods are supported by Firefox 4, Chrome 6, Safari 5, IE 9 and above.

注意,对象。密钥和其他ECMAScript 5方法得到了Firefox 4、Chrome 6、Safari 5、ie9和以上的支持。

For example:

例如:

var o = {"foo": 1, "bar": 2}; 
alert(Object.keys(o));

ECMAScript 5 compatibility table: http://kangax.github.com/es5-compat-table/

ECMAScript 5兼容表:http://kangax.github.com/es5-compat-table/。

Description of new methods: http://markcaudill.com/index.php/2009/04/javascript-new-features-ecma5/

新方法的描述:http://markcaudill.com/index.php/2009/04/javascript-new features-ecma5/。

#5


15  

I'm a huge fan of the dump function.

我是转储函数的超级粉丝。

http://ajaxian.com/archives/javascript-variable-dump-in-coldfusion 如何列出JavaScript对象的属性?

http://ajaxian.com/archives/javascript-variable-dump-in-coldfusion

#6


14  

Object.getOwnPropertyNames(obj)

Object.getOwnPropertyNames(obj)

This function also shows non-enumerable properties in addition to those shown by Object.keys(obj).

除了Object.keys(obj)之外,该函数还显示了不可枚举的属性。

In JS, every property has a few properties, including a boolean enumerable.

在JS中,每个属性都有一些属性,包括布尔枚举。

In general, non-enumerable properties are more "internalish" and less often used, but it is insightful to look into them sometimes to see what is really going on.

一般来说,不可枚举的属性更像“internalish”,而不是经常使用,但是有时候查看它们是很有见地的,看看到底发生了什么。

Example:

例子:

var o = Object.create({base:0})
Object.defineProperty(o, 'yes', {enumerable: true})
Object.defineProperty(o, 'not', {enumerable: false})

console.log(Object.getOwnPropertyNames(o))
// [ 'yes', 'not' ]

console.log(Object.keys(o))
// [ 'yes' ]

for (var x in o)
    console.log(x)
// yes, base

Also note how:

还请注意:

  • Object.getOwnPropertyNames and Object.keys don't go up the prototype chain to find base
  • 对象。getOwnPropertyNames和对象。钥匙不上原型链去寻找基地。
  • for in does
  • 因为在做

More about the prototype chain here: https://*.com/a/23877420/895245

关于原型链的更多信息:https://*.com/a/23877420/895245。

#7


13  

Could do it with jQuery as follows:

可以使用jQuery进行如下操作:

var objectKeys = $.map(object, function(value, key) {
  return key;
});

#8


8  

if you are trying to get the elements only but not the functions then this code can help you

如果您试图仅获取元素而不是函数,那么这段代码可以帮助您。

this.getKeys = function() {

    var keys = new Array();
    for(var key in this) {

        if( typeof this[key] !== 'function') {

            keys.push(key);
        }
    }
    return keys;
}

this is part of my implementation of the HashMap and I only want the keys, "this" is the hashmap object that contains the keys

这是我的HashMap实现的一部分,我只需要键,“this”是包含键的HashMap对象。

#9


7  

This will work in most browsers, even in IE8 , and no libraries of any sort are required. var i is your key.

这将在大多数浏览器中工作,即使在IE8中,也不需要任何类型的库。我是你的钥匙。

var myJSONObject =  {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"}; 
var keys=[];
for (var i in myJSONObject ) { keys.push(i); }
alert(keys);

#10


6  

Under browsers supporting js 1.8:

浏览器支持js 1.8:

[i for(i in obj)]

#11


5  

Mozilla has full implementation details on how to do it in a browser where it isn't supported, if that helps:

Mozilla有完整的实现细节,关于如何在不支持它的浏览器中实现它,如果有帮助的话:

if (!Object.keys) {
  Object.keys = (function () {
    var hasOwnProperty = Object.prototype.hasOwnProperty,
        hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
        dontEnums = [
          'toString',
          'toLocaleString',
          'valueOf',
          'hasOwnProperty',
          'isPrototypeOf',
          'propertyIsEnumerable',
          'constructor'
        ],
        dontEnumsLength = dontEnums.length;

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

      var result = [];

      for (var prop in obj) {
        if (hasOwnProperty.call(obj, prop)) result.push(prop);
      }

      if (hasDontEnumBug) {
        for (var i=0; i < dontEnumsLength; i++) {
          if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
        }
      }
      return result;
    };
  })();
}

You could include it however you'd like, but possibly in some kind of extensions.js file at the top of your script stack.

你可以把它包括在你想要的地方,但可能是在某种扩展中。js文件位于脚本堆栈的顶部。

#12


3  

IE does not support for(i in obj) for native properties. Here is a list of all the props I could find.

IE不支持本机属性(我在obj中)。这是我能找到的所有道具的清单。

It seems * does some stupid filtering.

看起来*做了一些愚蠢的过滤。

The list is available at the bottom of this google group post:- https://groups.google.com/group/hackvertor/browse_thread/thread/a9ba81ca642a63e0

该列表在谷歌组的底部可用:- https://groups.google.com/group/hackvertor/browse_thread/a9ba81ca642a63e0。

#13


3  

Since I use underscore.js in almost every project, I would use the keys function:

因为我使用下划线。在几乎每个项目中,我都会使用键函数:

var obj = {name: 'gach', hello: 'world'};
console.log(_.keys(obj));

The output of that will be:

其输出将是:

['name', 'hello']

#14


1  

Building on the accepted answer.

建立在公认的答案上。

If the Object has properties you want to call say .properties() try!

如果对象有属性,您需要调用。properties()尝试!

var keys = Object.keys(myJSONObject);

for (j=0; j < keys.length; j++) {
  Object[keys[i]].properties();
}

#15


0  

The solution work on my cases and cross-browser:

解决方案在我的案例和跨浏览器:

var getKeys = function(obj) {
    var type = typeof  obj;
    var isObjectType = type === 'function' || type === 'object' || !!obj;

    // 1
    if(isObjectType) {
        return Object.keys(obj);
    }

    // 2
    var keys = [];
    for(var i in obj) {
        if(obj.hasOwnProperty(i)) {
            keys.push(i)
        }
    }
    if(keys.length) {
        return keys;
    }

    // 3 - bug for ie9 <
    var hasEnumbug = !{toString: null}.propertyIsEnumerable('toString');
    if(hasEnumbug) {
        var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
            'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];

        var nonEnumIdx = nonEnumerableProps.length;

        while (nonEnumIdx--) {
            var prop = nonEnumerableProps[nonEnumIdx];
            if (Object.prototype.hasOwnProperty.call(obj, prop)) {
                keys.push(prop);
            }
        }

    }

    return keys;
};

#16


0  

You can use an object-values reusable component to get all of the object's values.

您可以使用对象值可重用组件来获取所有对象的值。

Example:

例子:

values({ a: 1, b: 2, c: 3 }) // => [1, 2, 3]

How it works:

它是如何工作的:

function values(object: {[any]: any}): any[] {
  const objValues = [];
  forEach(object, val => objValues.push(val)); 
  return objValues;
};

相关文章