[英]Javascript Map and Filter on two array
我有一個像這樣的數組:
arr = ['AD','CI','AI']
我有一個像
{
"AD": "Mailing Address",
"CI": "Additional Interest",
"HO": "Homeowners",
"AI": "Additional Interest"
}
在這里,對象包含鍵值對並形成數組鍵,該數組鍵如何將鍵與對象進行比較並獲取鍵的值。 如何從對象獲取數組鍵的值?
使用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);
這種單行代碼將為您提供包含對象值的數組result
。
let result = arr.map(a=>obj[a]);
你的情況需要數組嗎? 如果只需要對象的值,則可以執行以下操作:
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]}`));
希望這會有所幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.