0

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.

jasan
  • 8,391
  • 16
  • 45
  • 90

4 Answers4

1

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
}, {})
uladzimir
  • 5,469
  • 5
  • 28
  • 48
  • Installing a module to do native stuff doesn't feel right! – Pranesh Ravi Sep 24 '16 at 17:27
  • @PraneshRavi as I said, it's up to you use or not use the module. I think that state can be handled without redux, but you're using it for stuff that you can do natively. – uladzimir Sep 24 '16 at 17:34
  • 3
    Lodash's omit is my preferred way of accomplishing this. Using an external package to perform such a simple operation may not "feel right", but the reality is that the standard JavaScript API lacks many important operations. – David L. Walsh Sep 25 '16 at 05:21
1

If you use ES6, this is a single line work. And, I'm sure you are using ES6.

Hope it helps.

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

const { b, ...remaining} = a
console.log(remaining)
Pranesh Ravi
  • 15,581
  • 6
  • 40
  • 61
0

One way I can think of is using object destructuring:

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

let {a,c} = obj;
let newState = {a,c};
slugo
  • 949
  • 2
  • 10
  • 21
  • I should have been more clear, the nested objects could be hundreds so this solution might not be efficient. – jasan Sep 24 '16 at 16:57
  • Maybe [this](http://stackoverflow.com/questions/25553910/one-liner-to-take-some-properties-from-object-in-es-6) will help you then. – slugo Sep 24 '16 at 17:03
  • @jasan what is it that you don't understand ? – slugo Sep 24 '16 at 17:17
-1

In order to remove a state from a Redux Store, I did the following and it works:

case DELETE_SAVED_OBJECT :
  return Object.keys(state) // loops over the current state object and gets the keys
  .filter((Id) => action.Id !== Id) // filters out Id for deletion and return an array
  .reduce((prev, current) => { // turn the array back to an object
    prev[current] = state[current]
    return prev   // return the new state 
  }, {})
jasan
  • 8,391
  • 16
  • 45
  • 90