user3281384
user3281384

Reputation: 531

ImmutableJS - Dealing with list of objects?

I'm learning to use ImmutableJS but I'm a little confused. I looked at the documentation and I see there are Maps for objects and Lists for arrays.

So I build an object like: sampleTodo = Immutable.Map({text: 'Testing 1 2 3', status: 'Open'})

And then do: list = Immutable.List().push(sampleTodo)

Not sure if this is right. If it is, I get stuck when I have an index and have to return a modified List.

For example, if index is 0, I do:

list.get(index)

and get

Object {size: 1, _root: ArrayMapNode, __ownerID: undefined, __hash: undefined, __altered: false}

So, I don't see how I can set the status of the Map object to status: "Complete" by going through the List.

Upvotes: 3

Views: 3669

Answers (2)

Meistro
Meistro

Reputation: 3794

You can do this:

list = list.setIn([index, 'status'], 'Complete')

The key point to understand is that .setIn uses the the index of whatever the underlying data type is. Since list is a Immutable.List we can use an integer to look up the first element, which is a Immutable.Map. The "index" of an Immutable.Map is the object key(string), which is why you can also do

list = list.getIn([index, 'status']) to get the status of an item.

Upvotes: 2

user3281384
user3281384

Reputation: 531

I found a viable solution here: https://stackoverflow.com/a/29655323/3281384

list = list.update(
  list.findIndex(function(item) { 
    return item.get("name") === "third"; 
  }), function(item) {
    return item.set("count", 4);
  }
);

Or, in my case,:

list = list.update(
  index, function(todo) {
    return todo.set('status', 'Complete');
  }
);

Upvotes: 0

Related Questions