本文翻译自:Getting JavaScript object key list
I have a JavaScript object like 我有一个JavaScript对象,例如
var obj = {
key1: 'value1',
key2: 'value2',
key3: 'value3',
key4: 'value4'
}
How can I get the length and list of keys in this object? 如何获得此对象中键的长度和列表?
#1楼
参考:https://stackoom.com/question/cSgu/获取JavaScript对象键列表
#2楼
Underscore.js makes the transformation pretty clean: Underscore.js使转换非常干净:
var keys = _.map(x, function(v, k) { return k; });
Edit: I missed that you can do this too: 编辑:我想念你也可以这样做:
var keys = _.keys(x);
#3楼
Note that in coffeescript this can be accomplished in all browsers and node as 请注意,在coffeescript中,这可以在所有浏览器和节点中完成
k for k of obj
and thus 因此
(1 for _ of obj).length
#4楼
using slice, apply and join method. 使用切片,应用和联接方法。
var print = Array.prototype.slice.apply( obj );
alert('length='+print.length+' list'+print.join());
#5楼
For a comma-delineated string listing the keys of a JSON Object, try the following: 对于列出了JSON对象键的逗号分隔的字符串,请尝试以下操作:
function listKeys(jObj){
var keyString = '';
for(var k in jObj){
keyString+=(','+k);
}
return keyString.slice(1);
}
/* listKeys({'a' : 'foo', 'b' : 'foo', 'c' : 'foo'}) -> 'a,b,c' */
#6楼
Anurags answer is basically correct. 阿努拉格人的回答基本上是正确的。 But to support Object.keys(obj)
in older browsers as well you can use the code below that is copied from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys . 但是要在旧版浏览器中也支持Object.keys(obj)
,您可以使用从https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/复制的以下代码键 。 It adds the Object.keys(obj)
method if it's not available from the browser. 如果浏览器不可用,它将添加Object.keys(obj)
方法。
if (!Object.keys) {
Object.keys = (function() {
'use strict';
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 = [], prop, i;
for (prop in obj) {
if (hasOwnProperty.call(obj, prop)) {
result.push(prop);
}
}
if (hasDontEnumBug) {
for (i = 0; i < dontEnumsLength; i++) {
if (hasOwnProperty.call(obj, dontEnums[i])) {
result.push(dontEnums[i]);
}
}
}
return result;
};
}());
}