Why Immutable.js throws an invalid key path to Map.setIn ()

I need to skip something because Docs does it as if the code below worked fine, but I got an invalid keypath error ... Check this code .

var map1 = Immutable.Map({ 'selector': { 'type': 'bar' }}); var map2 = map1.setIn(['selector', 'type'], 'foo'); console.log(map2.toJS()); 
+8
javascript
source share
1 answer

This is because the 'selector' key has a value other than Map. setIn will work if we make sure that the value for 'selector' also an immutable map:

 var map1 = Immutable.Map({ 'selector': Immutable.Map({ 'type': 'bar' })}); var map2 = map1.setIn(['selector', 'type'], 'foo'); console.log(map1.toJS()); console.log(map2.toJS()); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.js"></script> 

To deeply convert JavaScript objects and arrays to Maps and Lists, you can use fromJS() . So you can easily write:

 var map3 = Immutable.fromJS({ 'selector': { 'type': 'bar' }}); var map4 = map3.setIn(['selector', 'type'], 'foo'); console.log(map3.toJS()); console.log(map4.toJS()); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.js"></script> 
+14
source share

All Articles