update object in array if id exists else append javascript

Solutions on MaxInterview for update object in array if id exists else append javascript by the best coders in the world

showing results for - "update object in array if id exists else append javascript"
Noha
14 Feb 2017
1function upsert(array, item) { // (1)
2  const i = array.findIndex(_item => _item.id === item.id);
3  if (i > -1) array[i] = item; // (2)
4  else array.push(item);
5}
6
7const array = [
8  {id: 0, name: 'Apple', description: 'fruit'},
9  {id: 1, name: 'Banana', description: 'fruit'},
10  {id: 2, name: 'Tomato', description: 'vegetable'}
11];
12
13upsert(array, {id: 2, name: 'Tomato', description: 'fruit'})
14console.log(array);
15/* =>
16[
17  {id: 0, name: 'Apple', description: 'fruit'},
18  {id: 1, name: 'Banana', description: 'fruit'},
19  {id: 2, name: 'Tomato', description: 'fruit'}
20]
21*/
22
23upsert(array, {id: 3, name: 'Cucumber', description: 'vegetable'})
24console.log(array);
25/* =>
26[
27  {id: 0, name: 'Apple', description: 'fruit'},
28  {id: 1, name: 'Banana', description: 'fruit'},
29  {id: 2, name: 'Tomato', description: 'fruit'},
30  {id: 3, name: 'Cucumber', description: 'vegetable'}
31]
32*/