Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Not updating value inside Map #44

Closed
NareshNaredla opened this issue Aug 8, 2014 · 2 comments
Closed

Not updating value inside Map #44

NareshNaredla opened this issue Aug 8, 2014 · 2 comments

Comments

@NareshNaredla
Copy link

Hai all,

Iam having a map like : var map = Immutable.Map({a:1, b:{d:2}, c:3});

now i want to update value of 'd'...and i tried the following :

  1. map.set(['b','d']),1000)
    2.map = map.updateIn(['b', 'd'], function(value) { return 1000; });// i know it is for nested map...

and not able to update ...so could you please suggest me how to update that value

@NareshNaredla
Copy link
Author

and tried like this also : map.set(['b','d'], function(value) { return 1000; })

@leebyron
Copy link
Collaborator

leebyron commented Aug 8, 2014

Since that value is a mutable object, not an immutable map, the immutable API does not apply to it (see Object's API). If your update backs up one level, then it points to the object instead of the key within the object:

var map1 = Immutable.Map({a:1, b:{d:2}, c:3});
var map2 = map1.update('b', function (value) { value.d = 1000; return value; })

However, note that this has mutated a mutable value, which your original map still points to, so in this case map2 === map1.

You could also return a copy of this object:

var map1 = Immutable.Map({a:1, b:{d:2}, c:3});
var map2 = map1.update('b', function (value) { 
  var newValue = {};
  for (var k in value) {
    if (value.hasOwnProperty(k)) {
      newValue[k] = value[k];
    }
  }
  newValue.d = 1000; 
  return newValue; 
})

And now map2 !== map1 and map1's mutable object has not been changed. However this highlights one of the use cases of Immutable Map. If you desired the second behavior, then using an immutable Map instead of a mutable Object as a nested value would provide an API much easier to work with:

var map1 = Immutable.Map({a:1, b:Immutable.Map({d:2}), c:3});
var map2 = map1.update('b', function (value) { return value.set('d', 1000); })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants