简体   繁体   中英

How to Compare and get the values two Array of objects?

I have two Array of objects as follows.

Array of object 1 ----> [{locationId:1,locationName:"Bangalore"},{locationId:2, locationName:"Mumbai"}]
Array of object 2 -----> [{baseId:1,baseUnit:"abc"},{baseId:2,baseUnit:""}]

Is there any short method where I can locationName from first Array, using baseId from Array 2 and push that to new Array of objects,in angular 6. I dont want to use for loop.

 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); 

The following code should do what you need (comments in code)

// 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);
    }
});

Reduce your arrays

Here you can see that it is possible to use .reduce on an Array to iterate over the array whilst generating a new one:

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]}), [])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM