Merge object / Object assign / Object extend
const obj1 = { a : 1 , b : 2 , c : 3 } ;
const obj2 = { c : 4 , d : 5 } ;
const obj3 = {
...obj1 ,
...obj2 ,
} ;
// obj3 === {a: 1, b:2, c:4, d: 5}
const obj1 = { a : 1 , b :2 , c : 3 } ;
const a = 4 ;
const c = 5 ;
const updatedObj1 = {
...obj1 ,
a,
c,
} ;
// updatedObj1 === {a: 4, b:2, c: 5}
const arr = [ 0 , 1 , 2 , 3 ] ;
const newItem = 4 ;
const updatedArr = [
...arr ,
newItem ,
] ;
// updatedArr = [0,1,2,3,4];
Prepend item into array (Unshift)
const arr = [ 1 , 2 , 3 , 4 ] ;
const newItem = 0 ;
const updatedArr = [
newItem ,
...arr ,
] ;
// updatedArr = [0,1,2,3,4];
Add array item in between
const arr = [ 0 , 1 , 2 , 3 , 4 , 5 ] ;
const indexToAdd = 3 ;
const itemToAdd = 6 ;
const updatedArr = [
...arr . slice ( 0 , indexToAdd ) ,
itemToAdd ,
...arr . slice ( indexToAdd + 1 ) ,
] ;
// updatedArr === [0,1,2,6,3,4,5];
const arr1 = [ 0 , 1 , 2 ] ;
const arr2 = [ 3 , 4 , 5 ] ;
const mergedArr = [
...arr1 ,
...arr2 ,
] ;
// mergedArr === [0,1,2,3,4,5]
const arr = [ 0 , 1 , 2 , 3 , 4 ] ;
const indexToRemove = 3 ;
const updatedArr = [
...arr . slice ( 0 , indexToRemove ) ,
...arr . slice ( indexToRemove + 1 ) ,
] ;
// updatedArr === [0,1,2,4]
And updating an object within the object: