21

I must be missing something here because the Docs make it out as if the below code should work just fine but I get an invalid keypath error... Check this codepen.

var map1 = Immutable.Map({ 'selector': { 'type': 'bar' }});
var map2 = map1.setIn(['selector', 'type'], 'foo');
console.log(map2.toJS());
Seth
  • 10,198
  • 10
  • 45
  • 68
hally9k
  • 2,423
  • 2
  • 25
  • 47

1 Answers1

38

This happens because the key 'selector' has a non-Map value. setIn will work if we make sure that the value for 'selector' is 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 more 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>
1983
  • 5,882
  • 2
  • 27
  • 39
  • So if I have a deeply nested object that I want to make changes to I have to recursively map every level of nesting manually? This seems a bit, well, cumbersome tbh. – hally9k Jun 08 '16 at 23:37
  • 2
    That was for illustration. You can use [`fromJS()`](https://facebook.github.io/immutable-js/docs/#/fromJS) to deeply convert JavaScript Objects and Arrays to Maps and Lists. – 1983 Jun 09 '16 at 00:17