The ability to reply to discussions is limited to PRO members. Want to join in the discussion? Click here to subscribe now.

Iterating Over an Immutable.js Map()

Iterating Over an Immutable.js Map()

6:31
Immutable.js provides several methods to iterate over an Immutable.Map(). These also apply to the other immutable structures found within the Immutable.js family, such as Set and List. The primary methods are map and forEach, but we will also cover filter and groupBy.
Watch this lesson now
Avatar
egghead.io

Immutable.js provides several methods to iterate over an Immutable.Map(). These also apply to the other immutable structures found within the Immutable.js family, such as Set and List. The primary methods are map and forEach, but we will also cover filter and groupBy.

Avatar
Noah

I am not sure why it is possible to do the stuff you do in markAllTodosAsComplete - doesn't this show that the Map is in fact not immutable?

In reply to egghead.io
Avatar
J.S.

Hey Noah! It shows that regular javascript objects remain mutable inside the immutable structure, but the structure itself cannot be mutated. It's somewhat confusing, I know. If you wanted everything to be immutable, then you'd need to make the Todos into Map()s themselves. Also that is using forEach(), which can produce side effects. Does that make sense?

In reply to Noah
Avatar
Sandeep

"return" is not required in the first line of markAllTodosAsComplete as we're not assigning the returned value back to todos. I know it doesn't matter but might avoid some confusion.

Avatar
Sandeep

Make the Todos into Map()s themselves -OR- use fromJS().

In reply to J.S.
Avatar
Ilyes

You could also use map instead of foreach:

function markAllTodosAsComplete(todos) {
    return todos.map(todo => {
        todo.completed = true;
        return todo;
    });
}
Avatar
Vlado Tesanovic

Function addTodo does not add elements in right order. In your example, you use getTodoTexts, and you are expecting text that is same on all objects "I'm a todo!", but try with to change getTodoTexts to return title instead of text, and try to fetch .first() element then expect "Todo0", it will fail and you will see that is not consistent.

Avatar
J.S.

Hi Vlado!

That's correct and expected. Immutable.Map() is unordered. If you need want order (at the cost of some performance) use Immutable.OrderedMap(). Here's a link to the docs: https://facebook.github.io/immutable-js/docs/#/OrderedMap

Thanks!
Leonard

In reply to Vlado Tesanovic
HEY, QUICK QUESTION!
Joel's Head
Why are we asking?