我有两个对象数组。假设商店阵列和国家/地区阵列。我想将Shop的对象的国家/地区代码映射到country的对象国家/地区,以创建一个新的对象数组。在新的对象数组中,一个对象应该看起来像一个Shop数组的一个对象具有{id:01,name:'name of the shop',countryCode:'USA'}
,Country数组的一个对象具有{code:'USA', country:'United States of America'}
这样。
{id:01,name:'name of the shop',countryCode:'USA',country:'United States of America'}
什么是最优化的方法
答案 0 :(得分:1)
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)
答案 1 :(得分:0)
您可以这样做。
let shopArr = [{id:01,name:'name of the shop',countryCode:'USA'}];
let countryArr = [{code:'USA', country:'United States of America'}];
let newArr = shopArr.map((shop) => {
return {...shop, country: countryArr.find(country => {country.code === shop.countryCode}).country};
});
答案 2 :(得分:0)
您可以做到
let shopArrayObj = [{ id: 01, name: "shop1", countryCode: 'USA' },
{ id: 02, name: "shop2", countryCode: 'US' },
{ id: 03, name: "shop3", countryCode: 'ENG' }]
let countryArrayObj = [{ code: 'USA', country: 'United States of America' },
{ code: 'ENG', country: 'England' }]
let finalArrayOb = []
shopArrayObj.map(shop => {
countryArrayObj.map(country => {
if (country.code === shop.countryCode) {
let obj = { ...shop, ...country, }
delete obj.code
finalArrayOb.push(obj)
}
})
})
console.log(finalArrayOb)
答案 3 :(得分:0)
您可以这样做:
let country1 = [{code:'USA', country:'United States of America'}]
let shop1 = [{id:01,name:'name of the shop',countryCode:'USA'}]
country1.forEach((item1) => {
shop1.forEach((item2) => {
if(item1.code === item2.countryCode) {
arr.push({'id': item2.id, 'name': item2.name, 'countryCode': item2.countryCode, 'country': item1.country})
}
})
})
希望这会有所帮助。
答案 4 :(得分:0)
您可以执行以下操作。
const array1 = [{ id: 1, name:'My Shop', countryCode:'USA' }, { id: 2, name:'My Shop2', countryCode:'UK' }];
const array2 = [{ code:'USA', country:'United States of America' }, { code:'UK', country:'United Kingdom' }];
let myArray = [];
array1.forEach(item1 => {
array2.forEach(item2 => {
if (item1.countryCode === item2.code) {
let obj = {...item1, country: item2.country };
myArray.push(obj)
}
});
});
答案 5 :(得分:0)
如果您可以将Country重组为对象而不是数组,则可以使用single for循环获得结果。工作代码如下。
var country = {
"USA": "United States of America",
"IN": "India",
"UAE": "United Arab Emirates",
"UK": "United Kingdom"
}
var shopArray = [{id:01,name:'name of the shop',countryCode:'USA'}, {id:02,name:'name of another shop',countryCode:'UK'}]
for(var i=0;i<shopArray.length; i++){
var countryCode = shopArray[i].countryCode;
shopArray[i].country = country[countryCode];
}
console.log(shopArray)
此代码实际上将修改原始的shopArray,而不是提供新的数组。