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

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

检索属性名列表的最佳方法是什么?例如,我想以一些变量“键”结束,这样:

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

当前回答

这里有很多答案…这是我的意见。

我需要一些东西来打印出所有的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));

希望这也能有所帮助。

其他回答

在ES6及后续版本(ECMAScript 2015)中,你可以获得所有属性,如下所示:

let keys = Object.keys(myObject);

如果你想列出所有的值

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

我是转储功能的超级粉丝。

ajax»JavaScript变量转储在Coldfusion

下载转储功能

如果你只是想获取元素,而不是函数,那么这段代码可以帮助你

this.getKeys = function() {

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

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

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

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

在支持js 1.8的浏览器下:

[i for(i in obj)]

以公认的答案为基础。

如果对象有你想要调用的属性,那么说.properties()试试!

var keys = Object.keys(myJSONObject);

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