[英]Get value from Javascript object using for loop
I am having an issue getting accessing the value from a key of an object. 我在从对象的键访问值时遇到问题。
I am passing in this.fields
which has 2 objects in an array like, 我传入
this.fields
,它有一个数组中的2个对象,如,
[{'First Name': 'firstName'}, {'Last Name': 'lastName'}]
I am able to get the keys using the Object.keys
function, but cannot figure out how to get the values associated with them. 我能够使用
Object.keys
函数获取密钥,但无法弄清楚如何获取与它们相关的值。
let properties = [];
for (let field of this.fields) {
console.log(field);
properties.push({
"name": Object.keys(field),
"value": ""
});
}
I have tried doing this.fields[field]
to get it, but it is returning undefined. 我试过这个
this.fields[field]
得到它,但它返回undefined。 Any advice on how to approach this? 关于如何处理这个问题的任何建议?
let properties = [];
for (let field of this.fields) {
for (let prop in field) {
properties.push({ "name": prop, "value": field[prop] });
}
}
If you have only one key/value pair, you can do: 如果您只有一个键/值对,则可以执行以下操作:
let key = Object.keys(field)[0];
let value = field[key];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.