19

I have a map with this structure:

{
1: {},
2: {}
}

And I'd like to delete 2: {} from it (of course - return new collection without this). How can I do it? I tried this, but something is wrong:

 theFormerMap.deleteIn([],2) //[] should mean that it's right in the root of the map, and 2 is the name of the object I want to get rid of
user3696212
  • 3,381
  • 5
  • 18
  • 31

3 Answers3

20

Just use the delete method and the property in double quotes:

theFormerMap = theFormerMap.delete("2")
Johann Echavarria
  • 9,695
  • 4
  • 26
  • 32
  • 1
    Thanks, I have even tried this, but accidentally found where the problem was - the argument has to be string. I've given there a number, so for everyone - be careful about this. – user3696212 Jun 30 '15 at 11:51
  • ..which brings me to the fact that your solution wouldn't work, because your argument was String, but a number was needed. Anyway, thanks for the info about delete() method. – user3696212 Jun 30 '15 at 14:22
  • Remember you can show your code running here in a Stack Overflow Code Snippet – Johann Echavarria Jul 03 '15 at 16:19
  • Some JSLint tests recommend the use of double quotes and this denotes a String of data. Check out the following for more details. https://www.youtube.com/watch?v=5YZZp7HsQXY – Garry Taylor Aug 09 '16 at 19:31
7

Just use the delete method and pass the property you want to delete:

theFormerMap = theFormerMap.delete(2)

If this does not work then you have probably created theFormerMap using fromJS:

Immutable.fromJS({1: {}, 2: {}}).delete(2)
=> Map { "1": Map {}, "2": Map {} }

Key 2 is not removed as it is, in fact, a string key. The reason is that javascript objects convert numeric keys to strings.

However Immutable.js does support maps with integer keys if you construct them without using fromJS:

Immutable.Map().set(1, Immutable.Map()).set(2, Immutable.Map()).delete(2)
=> Map { 1: Map {} }
gabrielf
  • 2,210
  • 1
  • 19
  • 11
  • And if you would like to use `deleteIn` to remove key 2 you call it like: `theFormerMap.deleteIn([2])` – gabrielf Jul 06 '16 at 07:22
-5

If you use immutable-data:

var immutableData = require("immutable-data")
var oldObj = {
  1: {},
  2: {}
}
var data = immutableData(oldObj) 
var immutableObj = data.pick()

//modify immutableObj by ordinary javascript method
delete immutableObj[2]

var newObj = immutableObj.valueOf()

console.log(newObj)                  // { '1': {} }
console.log(newObj===oldObj)         // [ { a: '2', b: '2' } ]
console.log(newObj[1]===oldObj[1])   // true
yaya
  • 1
  • 1