Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

update object in array if id exists else append javascript

function upsert(array, item) { // (1)
  const i = array.findIndex(_item => _item.id === item.id);
  if (i > -1) array[i] = item; // (2)
  else array.push(item);
}

const array = [
  {id: 0, name: 'Apple', description: 'fruit'},
  {id: 1, name: 'Banana', description: 'fruit'},
  {id: 2, name: 'Tomato', description: 'vegetable'}
];

upsert(array, {id: 2, name: 'Tomato', description: 'fruit'})
console.log(array);
/* =>
[
  {id: 0, name: 'Apple', description: 'fruit'},
  {id: 1, name: 'Banana', description: 'fruit'},
  {id: 2, name: 'Tomato', description: 'fruit'}
]
*/

upsert(array, {id: 3, name: 'Cucumber', description: 'vegetable'})
console.log(array);
/* =>
[
  {id: 0, name: 'Apple', description: 'fruit'},
  {id: 1, name: 'Banana', description: 'fruit'},
  {id: 2, name: 'Tomato', description: 'fruit'},
  {id: 3, name: 'Cucumber', description: 'vegetable'}
]
*/
Comment

PREVIOUS NEXT
Code Example
Javascript :: require a json as a string 
Javascript :: get element by id jqueryt 
Javascript :: change image src using jquery 
Javascript :: alphabet to number javascript 
Javascript :: es6 method definition syntax 
Javascript :: fuse.js npm 
Javascript :: js if dark mode 
Javascript :: complete math objects in javascript 
Javascript :: finddomnode is deprecated in strictmode 
Javascript :: chart js in angular 13 
Javascript :: != vs !== javascript 
Javascript :: react native only 1 corner rounded 
Javascript :: jquery select first matching element 
Javascript :: javascript fibonacci example 
Javascript :: express-async-errors 
Javascript :: js largura da tela 
Javascript :: include js to js 
Javascript :: jquery parent 
Javascript :: javascript code to calculate compound interest 
Javascript :: js how to filter only real numbers from decimals 
Javascript :: how to get an array from another script in js 
Javascript :: live vue js port number 
Javascript :: react click outside 
Javascript :: how to insert html into javascript 
Javascript :: javascript convert to array 
Javascript :: mongodb replace root 
Javascript :: javascript sum of arguments 
Javascript :: add dark mode to react 
Javascript :: parse string to int nodejs 
Javascript :: jquery import js file 
ADD CONTENT
Topic
Content
Source link
Name
1+1 =