Guest User

Untitled

a guest
Apr 21st, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.71 KB | None | 0 0
  1. const array1 = [
  2. {id: 1, name: "Foo Smith", isProv: true},
  3. {id: 2, name: "CAA", isProv: true}
  4. ];
  5.  
  6. const array2 = [
  7. {id: 2, name: "CAA"},
  8. {id: 3, name: "Bar Jones"}
  9. ];
  10.  
  11. // create map of the first array
  12. const mapArr1 = {};
  13. array1.forEach(v => {
  14. mapArr1[v.id] = v;
  15. })
  16.  
  17. // iterate over second array
  18. array2.forEach(v => {
  19. if(mapArr1[v.id]) { // check if object with the same id exist in first array
  20.  
  21. // here you can do any kind of checks to both objects
  22.  
  23. // in this case, we just merge both objects
  24. mapArr1[v.id] = Object.assign({}, mapArr1[v.id], v);
  25.  
  26.  
  27. } else { // if not, save the new value
  28. mapArr1[v.id] = v;
  29. }
  30.  
  31. });
  32.  
  33. const result = Object.keys(mapArr1).map(k => mapArr1[k]);
Add Comment
Please, Sign In to add comment