我有一个像这样的数组:
arr = ['AD','CI','AI']
我有一个像
的对象{
"AD": "Mailing Address",
"CI": "Additional Interest",
"HO": "Homeowners",
"AI": "Additional Interest"
}
在此对象包含键值对并形成数组键,该数组键如何将键与对象进行比较并获取键的值。 如何从对象获取数组键的值?
答案 0 :(得分:1)
使用Array.forEach()
遍历数组并从对象获取值:
var arr = ['AD','CI','AI'];
var obj = {"AD": "Mailing Address","CI": "Additional Interest","HO":"Homeowners","AI": "Additional Interest"};
arr.forEach(key => console.log(obj[key]));
如果您想在循环中进一步使用该值,则将其设置为多行,例如:
var arr = ['AD','CI','AI'];
var obj = {"AD": "Mailing Address","CI": "Additional Interest","HO":"Homeowners","AI": "Additional Interest"};
arr.forEach((key) => {
//some processing here
console.log(obj[key]);
});
使用map()
获取这些值的数组:
var arr = ['AD','CI','AI'];
var obj = {"AD": "Mailing Address","CI": "Additional Interest","HO":"Homeowners","AI": "Additional Interest"};
var res = arr.map((key) => obj[key]);
console.log(res);
答案 1 :(得分:1)
这种单行代码将为您提供包含对象值的数组result
。
let result = arr.map(a=>obj[a]);
答案 2 :(得分:0)
您的情况需要阵列吗?如果只需要对象的值,则可以执行以下操作:
const obj = {
"AD": "Mailing Address",
"CI": "Additional Interest",
"HO": "Homeowners",
"AI": "Additional Interest"
};
Object.entries(obj).forEach(([key, value]) => console.log(`${key}: ${value}`));
或
const obj = {
"AD": "Mailing Address",
"CI": "Additional Interest",
"HO": "Homeowners",
"AI": "Additional Interest"
};
Object.keys(obj).forEach((key) => console.log(`${obj[key]}`));
希望这会有所帮助!