Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const array1 = [
- {id: 1, name: "Foo Smith", isProv: true},
- {id: 2, name: "CAA", isProv: true}
- ];
- const array2 = [
- {id: 2, name: "CAA"},
- {id: 3, name: "Bar Jones"}
- ];
- // create map of the first array
- const mapArr1 = {};
- array1.forEach(v => {
- mapArr1[v.id] = v;
- })
- // iterate over second array
- array2.forEach(v => {
- if(mapArr1[v.id]) { // check if object with the same id exist in first array
- // here you can do any kind of checks to both objects
- // in this case, we just merge both objects
- mapArr1[v.id] = Object.assign({}, mapArr1[v.id], v);
- } else { // if not, save the new value
- mapArr1[v.id] = v;
- }
- });
- const result = Object.keys(mapArr1).map(k => mapArr1[k]);
Add Comment
Please, Sign In to add comment