[英]Accessing data within an unknown object name
Let's say I have some JSON:假设我有一些 JSON:
{
"An unknown value": {
"some": "values",
"I": "want",
"to": "access"
}
}
As you can see, I want to access the data within an object with an unknown name.如您所见,我想访问名称未知的对象中的数据。 This code will run in a Node.js environment.此代码将在 Node.js 环境中运行。 Any help is appreciated.任何帮助表示赞赏。
https://jsfiddle.net/ygac8dgg/ https://jsfiddle.net/ygac8dgg/
var object = {
"An unknown value": {
"some": "values",
"I": "want",
"to": "access"
},
"Another":"is",
"still":"uknown"
};
for (var property in object) {
if (object.hasOwnProperty(property)) {
// do stuff
console.log("property:",property);
console.log("value:",object[property]);
}
}
For everyone's reference, here's RobG 's suggestion as a fiddle:供大家参考,这里是RobG的建议:
https://jsfiddle.net/m4jgyvp0 https://jsfiddle.net/m4jgyvp0
const object = {
'An unknown value': {
'some': 'values',
'I': 'want',
'to': 'access'
},
'Another': 'is',
'still': 'unknown'
};
const keys = Object.keys(object);
const array = keys.map(key => ({ key: key, value: object[key] }));
keys
can be converted to an array of key-value pairs with the .map()
function, or you could iterate over keys
with .forEach()
. keys
可被转化为键-值对的阵列与.map()
函数,或者你可以遍历keys
与.forEach()
Reading my question again, it is very vague/unclear, and I can't seem to remember the context of this.再次阅读我的问题,它非常模糊/不清楚,我似乎不记得这个问题的上下文。
However in other situations, where I need to access an object via a dynamic key, one can use:但是在其他情况下,我需要通过动态键访问对象,可以使用:
const key: string = "aKeyFromSomeWhere"
const value = object[key]
rather than object.aKnownKey
而不是object.aKnownKey
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.