Guest User

Untitled

a guest
May 23rd, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. /***************************************************/
  2. /** Merge 2 arrays of objects using underscore.js **/
  3. /***************************************************/
  4.  
  5. //arr2 will be merged into arr1, arr1 will be extended as needed.
  6.  
  7. var arr1 = [{name: "lang", value: "English"}, {name: "age", value: "18"}];
  8. var arr2 = [{name : "childs", value: '5'}, {name: "lang", value: "German"}];
  9.  
  10. function mergeByProperty(arr1, arr2, prop) {
  11. _.each(arr2, function(arr2obj) {
  12. var arr1obj = _.find(arr1, function(arr1obj) {
  13. return arr1obj[prop] === arr2obj[prop];
  14. });
  15.  
  16. //If the object already exist extend it with the new values from arr2, otherwise just add the new object to arr1
  17. arr1obj ? _.extend(arr1obj, arr2obj) : arr1.push(arr2obj);
  18. });
  19. }
  20.  
  21. mergeByProperty(arr1, arr2, 'name');
  22.  
  23. console.log(arr1);
  24. //[{name: "lang", value: "German"}, {name: "age", value: "18"}, {name : "childs", value: '5'}]
Add Comment
Please, Sign In to add comment