Working with arrays and objects without mutating

Removing an element from an array, instead of .pop use

myArray.filter(element => element !== 'removeMe');

Adding an element to an array, instead of .push use

[...myArray, 'addMe'];

//reducer example
export default (state = [], action) => {
    switch (action.type) {
        case 'FETCH_POSTS':
            return action.payload;
        case 'ADD_POST':
            return [...state, action.payload];
        default:
            return state;
    }
}

Replacing an element in an array, instead of myArray[0] = ‘New Value’, use:

myArray.map(el => el === 'valueToBeChanged' ? 'New Value' : el)

Updating a property in an object, instead of myObject.name = ‘Joe’, use:

{ ...myObject, name: 'Joe'}

Adding a property to an object, instead of myObject.name = ‘Joe’, use:

{...myObject, name: 'Joe'}

Removing a property from an object, instead of delete myObject.name , there are a few different ways:

Recommended way: use lodash package

_.omit(myObject, 'name')

option 2. set the value to undefined

{...myObject, name: undefined}

option 3. Create a removeProp helper function that removes a prop and returns a new object.

removeProp = (obj, prop) => {
  let {[prop]: omit, ...res} = obj
  return res
}
const myObject2 = removeProp(myObject, 'name');

to avoid declaring a new variabel called myObject2
you can simply pass in the return value

removeProp = (obj, prop) => {
  let {[prop]: omit, ...res} = obj
  return res
}
console.log(removeProp(myObject, 'name'));

Add your comment