如何列出JavaScript对象的属性?

970

假设我这样创建了一个对象:

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

如何最好地检索属性名称列表?也就是说,我想最终得到一些变量'keys',使其具有以下特点:

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

3
有一点跑题,但如果你使用underscore.js:_.keys(myJSONObject) - Endy Tjahjono
5
如果您仅想获取可枚举的属性,请使用 Object.keys(obj)。但有时您也需要获取不可枚举的属性。如果需要获取这些属性,请记住使用 Object.getOwnPropertyNames(obj)。参考来源:https://dev59.com/9nVC5IYBdhLWcg3wsTfv#32413145 - Andrew
18个回答

8

如果有帮助的话,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;
    };
  })();
}

您可以按照自己的喜好将其包含在某种类型的 extensions.js 文件中,位于脚本堆栈的顶部。


MDN的实现是基于Andy E的实现,而Andy E的实现已经被作为答案给出。 - outis

8

在支持js 1.8的浏览器中:

[i for(i in obj)]

这不是JavaScript,是吗?至少Chrome和Node.js似乎都无法解析它。看起来很像Python。 - Christian Fritz

7

使用ES6及其之后的版本(ECMAScript 2015),您可以像这样获取所有属性:

let keys = Object.keys(myObject);

如果你想列出所有的值:

let values = Object.keys(myObject).map(key => myObject[key]);

let valudes = Object.values(myObject) 也能正常工作。 - Tomas

6

基于已接受的答案,继续讲解。如果该对象具有你想要调用的属性,比如 .properties(),请尝试!

var keys = Object.keys(myJSONObject);

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

5

由于我在几乎每个项目中都使用underscore.js,因此我会使用keys函数:

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

那样的输出将会是:
['name', 'hello']

这是一个工具集库,用于经常使用的JavaScript功能:http://underscorejs.org/ - schmijos

4
很多答案在这里... 这是我的意见。
我需要打印出所有JSON属性,包括具有子对象或数组的属性(包括父名称)。
所以 - 针对此JSON:
mylittleJson = {
  "one": "blah",
  "two": {
      "twoone": "",
      "twotwo": "",
      "twothree": ['blah', 'blah']
  },
  "three": ""
}

它将打印出以下内容:

.one
.two.twoone
.two.twotwo
.two.twothree
.three

这是一个函数

function listatts(parent, currentJson){
   var attList = []
   if (typeof currentJson !== 'object' || currentJson == undefined || currentJson.length > 0) {
      return
   }
   for(var attributename in currentJson){
       if (Object.prototype.hasOwnProperty.call(currentJson, attributename)) {
           childAtts = listatts(parent + "." + attributename, currentJson[attributename])
           if (childAtts != undefined && childAtts.length > 0)
               attList = [...attList, ...childAtts]
           else 
               attList.push(parent + "." + attributename)
       }
   }
   return attList
}

mylittleJson = {
  "one": "blah",
  "two": {
      "twoone": "",
      "twotwo": "",
      "twothree": ['blah', 'blah']
  },
  "three": ""
}

console.log(listatts("", mylittleJson));

希望这也能有所帮助。


4

1

这个解决方案适用于我的情况,并且跨浏览器。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接