Skip to content

Instantly share code, notes, and snippets.

@mknparreira
Last active September 21, 2023 14:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mknparreira/3e5274393120c5c056f5f90bb0b9d346 to your computer and use it in GitHub Desktop.
Save mknparreira/3e5274393120c5c056f5f90bb0b9d346 to your computer and use it in GitHub Desktop.
Javascript | Replacing objects in array (Updating) JavaScript

I need to replace objects in arr1 with items from arr2 with same id

var arr1 = [
  { id: '124', name: 'qqq'}, 
  { id: '589', name: 'www'}, 
  { id: '45', name: 'eee'}, 
  { id: '567', name: 'rrr'}
];

var arr2 = [
  { id: '124', name: 'ttt'}, 
  { id: '45', name: 'yyy'}
 ];

var res = arr1.map(obj => arr2.find(o => o.id === obj.id) || obj);

console.log(res);

// Result

[
  {"id": "124", "name": "ttt"},
  {"id": "589", "name": "www"},
  {"id": "45", "name": "yyy"},
  {"id": "567", "name": "rrr"}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment