jasan jasan - 2 months ago 12
React JSX Question

how can I remove a nested object state without mutating?

One way is to use Slice but is it compatible with nested objects or is it just for arrays., If so how would I slice a nested object ? i.e my state is

Object = {
a:{ 1: '1', 2: '2', 3: '3' },
b:{ 1: '1', 2: '2', 3: '3' },
c:{ 1: '1', 2: '2', 3: '3' }
}


and I want to remove b from Object.

Answer

If you can use lodash, I'd recommend to use omit method

Then you will be able to do:

const omit = require('lodash.omit')
const obj = { 
  a:{ 1: '1', 2: '2', 3: '3' }, 
  b:{ 1: '1', 2: '2', 3: '3' }, 
  c:{ 1: '1', 2: '2', 3: '3' } 
}

const objWithoutB = omit(obj, 'b')

Or you can do it by hands:

const keys = Object.keys(obj).filter((key) => key !== 'b')

const objectWithoutB = keys.reduce((acc, key) => {
  acc[key] = key
  return acc
}, {})