获取JavaScript对象键列表

本文翻译自: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;
};
}());
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值