假设我这样创建一个对象:
var myObject =
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
检索属性名列表的最佳方法是什么?例如,我想以一些变量“键”结束,这样:
keys == ["ircEvent", "method", "regex"]
假设我这样创建一个对象:
var myObject =
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
检索属性名列表的最佳方法是什么?例如,我想以一些变量“键”结束,这样:
keys == ["ircEvent", "method", "regex"]
当前回答
Object.getOwnPropertyNames (obj)
除了Object.keys(obj)所显示的属性外,该函数还显示不可枚举的属性。
在JS中,每个属性都有几个属性,包括一个布尔枚举。
一般来说,不可枚举的属性更“内在化”,使用也更少,但有时深入研究它们以了解真正发生的事情是很有见地的。
例子:
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(种(o)) // ['yes'] For (var x in o) console.log (x) //是的,base
还要注意如何:
对象。getOwnPropertyNames和Object。钥匙不是沿着原型链往上找底座的 For in
更多关于原型链的信息,请访问:https://stackoverflow.com/a/23877420/895245
其他回答
以公认的答案为基础。
如果对象有你想要调用的属性,那么说.properties()试试!
var keys = Object.keys(myJSONObject);
for (var j=0; j < keys.length; j++) {
Object[keys[j]].properties();
}
我是转储功能的超级粉丝。
ajax»JavaScript变量转储在Coldfusion
下载转储功能
这可以在大多数浏览器中工作,甚至在IE8中,并且不需要任何类型的库。Var I是你的钥匙。
var myJSONObject = {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
var keys=[];
for (var i in myJSONObject ) { keys.push(i); }
alert(keys);
这里有很多答案…这是我的意见。
我需要一些东西来打印出所有的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));
希望这也能有所帮助。
因为我几乎在每个项目中都使用了underscore.js,所以我会使用keys函数:
var obj = {name: 'gach', hello: 'world'};
console.log(_.keys(obj));
它的输出将是:
['name', 'hello']