javascript - 将对象数组中的一个属性映射到不同对象数组中的另一个对象
问题描述
我有两个对象数组。假设商店阵列和国家阵列。商店数组的一个对象{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'}
什么是最优化的方法来做到这一点
解决方案
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)
推荐阅读
- hadoop - 发生此类错误时该怎么办?
- telegram - Telegram BOT API:如何更改照片(不是标题)
- iphone - 在 Swift 中获取 iPhone 日期和时间设置
- swift - 将 pod 更新到 Firebase 5.4 后的 Firebase 错误
- c# - 将正整数添加到 int 会导致它变为负数
- java - 在分布式缓存 l2 上使用 infinispan 和休眠进行连接锁定
- sql - 连接来自两个数字列的值 + 添加额外的 0
- elixir - 凤凰应用启动时调用函数
- amazon-web-services - AWS Sagemaker - “在数据路径中找到隐藏文件!在训练之前将其删除。”
- swift - 从 '(_) throws -> ()' 类型的抛出函数到非抛出函数类型 '(CallResult) -> Void' 的无效转换