在不知道属性名称的情况下访问 JavaScript 的对象属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16576457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing a JavaScript's object property without knowing that property name
提问by Jamie Hutber
Situation
情况
I have a JSON object which is returned. And Below is an example of one. The who
in this particular example can change to whatever property name is required. So for example next time this will be name
rather than who
我有一个返回的 JSON 对象。下面是一个例子。在who
这个特定的例子可以改变任何属性名称要求。所以例如下一次这将name
而不是who
[{"who":"Arthur"},{"who":"Craig"},{"who":"Dan"},{"who":"Daniel"},{"who":"Frank"},{"who":"Ian"},{"who":"jamie"},{"who":"Jason"},{"who":"jaz"},{"who":"Liam"},{"who":"Paul"},{"who":"Shaun"},{"who":"Wayne"}]
Problem
问题
In my JS I need to be able to refer to the property and access its data without using its name as the name will always be something different.
在我的 JS 中,我需要能够在不使用其名称的情况下引用该属性并访问其数据,因为名称总是不同的。
What I have tried
我试过的
data.forEach(function(m){
console.info(m); // Object { who="Craig"}
console.info(m.who); // Craig, as expected
console.info(m[0]); // now not sure who to get it if who changes to name
});
回答by Rick Viscomi
Object.keys(m)[0]
should return the first enumerable property name in the object m
.
Object.keys(m)[0]
应该返回对象中的第一个可枚举属性名称m
。
So if m = {"who": "Arthur"};
then m[Object.keys(m)[0]]
will be "Arthur"
.
所以如果m = {"who": "Arthur"};
那时m[Object.keys(m)[0]]
将是"Arthur"
。
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys
Alternatively: Object.values(m)[0]
. See Object.values
或者:Object.values(m)[0]
。见Object.values
回答by hitautodestruct
You can also use the for in
loop:
您还可以使用for in
循环:
data.forEach( function ( m ) {
for ( var key in m ) {
console.log( key ); // "who"
console.log( m[key] ); // "Arthur"
}
});
The above would also work for multiple key: value
pairs in your object i.e:
以上也适用key: value
于您的对象中的多对,即:
[ {"who":"Arthur","who":"Fred"} ]
回答by Alec Henninger
If you always expect these objects to have only one property, you could do something like this:
如果你总是希望这些对象只有一个属性,你可以这样做:
var name, person;
for (person in data) {
for (name in data[person]) {
console.log(data[person][name]);
}
}
This would enumerate through each property of each person in the data. Because there is only one property per person (I assume), it will just enumerate that one property and stop, allowing you to use that property regardless of its name.
这将枚举数据中每个人的每个属性。因为每个人只有一个属性(我假设),它只会枚举该属性并停止,允许您使用该属性而不管其名称如何。