首页 > 解决方案 > 将对象数组中的一个属性映射到不同对象数组中的另一个对象

问题描述

我有两个对象数组。假设商店阵列和国家阵列。商店数组的一个对象{id:01,name:'name of the shop',countryCode:'USA'}和国家数组的一个对象{code:'USA', country:'United States of America'}我想将商店对象的国家代码映射到国家的对象国家创建新对象数组。在新对象数组中,一个对象应该如下所示。

{id:01,name:'name of the shop',countryCode:'USA',country:'United States of America'}

什么是最优化的方法来做到这一点

标签: javascripttypescript

解决方案


let shopArray=[{id:01,name:'name of the shop',countryCode:'USA'}] 
let countryArray=[{code:'USA', country:'United States of America'}]

let mapedShopArray=shopArray.map(eachShop=>{
    
    for(let eachCountry of countryArray){
        if(eachCountry.code==eachShop.countryCode){
            eachShop.country =eachCountry.country;
            break;
        }
    }

    return eachShop;
})

console.log(mapedShopArray)


推荐阅读