Remove a property in an object immutably

2019-03-07 21:00发布

I am using Redux. In my reducer I'm trying to remove a property from an object like this:

const state = {
    a: '1',
    b: '2',
    c: {
       x: '42',
       y: '43'
    },
}

And I want to have something like this without having to mutate the original state:

const newState = {
    a: '1',
    b: '2',
    c: {
       x: '42',
    },
}

I tried:

let newState = Object.assign({}, state);
delete newState.c.y

but for some reasons, it deletes the property from both states.

Could help me to do that?

14条回答
Anthone
2楼-- · 2019-03-07 21:09
function dissoc(key, obj) {
  let copy = Object.assign({}, obj)
  delete copy[key]
  return copy
}

Also, if looking for a functional programming toolkit, look at Ramda.

查看更多
贼婆χ
3楼-- · 2019-03-07 21:12

Just use ES6 object destructuring feature

const state = {
    c: {
       x: '42',
       y: '43'
    },
}

const { c: { y, ...c } } = state // generates a new 'c' without 'y'

console.log({...state, c }) // put the new c on a new state

查看更多
乱世女痞
4楼-- · 2019-03-07 21:12

It's easy with Immutable.js:

const newState = state.deleteIn(['c', 'y']);

description of deleteIn()

查看更多
劳资没心,怎么记你
5楼-- · 2019-03-07 21:15

You can use _.omit(object, [paths]) from lodash library

path can be nested for example: _.omit(object, ['key1.key2.key3'])

查看更多
地球回转人心会变
6楼-- · 2019-03-07 21:15

How about this:

function removeByKey (myObj, deleteKey) {
  return Object.keys(myObj)
    .filter(key => key !== deleteKey)
    .reduce((result, current) => {
      result[current] = myObj[current];
      return result;
  }, {});
}

It filters the key that should be deleted then builds a new object from the remaining keys and the initial object. The idea is stolen from Tyler McGinnes awesome reactjs program.

JSBin

查看更多
【Aperson】
7楼-- · 2019-03-07 21:15

You may use Immutability helper in order to unset an attribute, in your case:

import update from 'immutability-helper';

const updatedState = update(state, {
  c: {
    $unset: ['y']
  }
});    
查看更多
登录 后发表回答