[英]How to Compare and get the values two Array of objects?
我有兩個對象數組,如下所示。
對象1的數組----> [{locationId:1,locationName:"Bangalore"},{locationId:2, locationName:"Mumbai"}]
對象2的數組-----> [{baseId:1,baseUnit:"abc"},{baseId:2,baseUnit:""}]
有沒有什么短方法可以使用第2個數組中的baseId將第一個數組中的locationName定位到角度為6的新對象數組中?我不想使用for循環。
var a = [{locationId:1,locationName:"Bangalore"},{locationId:2, locationName:"Mumbai"}]; var b = [{baseId:1,baseUnit:"abc"},{baseId:2,baseUnit:""}] var c = []; a.map(obj => { b.map(res => { if (obj.locationId == res.baseId) { c.push({ "locationName": obj.locationName, "baseUnit": res.baseUnit }); } }); }); console.log(c);
以下代碼應滿足您的要求(代碼中的注釋)
// Go throught first array
newArray = array1.map(location => {
// Look for corresponding object in second array based on Ids
const foundBase = array2.find(base => base.baseId === location.locationId);
// If the object is found, return combined object
if(foundBase){
return Object.assign(location, foundBase);
}
});
在這里您可以看到,可以在Array
上使用.reduce
來迭代該數組,同時生成一個新數組:
let array1 = [{locationId:1,locationName:"Bangalore"},{locationId:2, locationName:"Mumbai"}]
let array2 = [{baseId:1,baseUnit:"abc"},{baseId:2,baseUnit:""}]
// Combine objects in array
array1.reduce((newArray, _, index) => newArray.concat({...array1[index], ...array2[index]}), [])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.