javascript - Using immutability-helper with Array, Object, Map - Stack Overflow

PHOTO EMBED

Thu Oct 01 2020 15:10:36 GMT+0000 (Coordinated Universal Time)

Saved by @winxton #javascript

import update from 'immutability-helper';

const oldArray = [
    {name: 'Stacey', age: 55},
    {name: 'John', age: 77},
    {name: 'Kim', age: 62},
];

// add an item
const newArray = update(oldArray, {$push: [
    {name: 'Trevor', age: 45},
]});

// replace an item
const itemIndex = 1; // replace *John* at index `1`
const newValue = {name: 'Kevin', age: 25};
const newArray = update(oldArray, { [itemIndex]: {$set: newValue} });

// modify an item
const itemIndex = 1; // modify *John* at index `1`
const newArray = update(oldArray, {
    [itemIndex]: {$merge, {
        age: 85, // change John's age to 85
    }}
});         

// remove an item
const itemIndex = 0; // delete *Stacey* at index `0`
const newArray = update(oldArray, {$splice: [[itemIndex, 1]] } });
content_copyCOPY

https://stackoverflow.com/questions/55436821/using-immutability-helper-with-array-object-map