How to map over key-values in a map to produce another map with ImmutableJS?
Asked Answered
C

2

9

How, using ImmutableJS, do I produce a new map by mapping over the key/value pairs of an input map?

In Scala, I would do something like this:

scala> Map(1->2, 3->4).toSeq.map{case (k, v) => (k*k) -> (v*v*v)}.toMap
res1: scala.collection.immutable.Map[Int,Int] = Map(1 -> 8, 9 -> 64)

(This case trivially squares the key and cubes the value.)

In JavaScript, I'm hoping for something like:

Immutable.fromJS({1: 2, 3: 4}).map((v, k) => [k*k, v*v*v]).toJS()
// { 1: 8, 9: 64 }

(I'm using ES6 via Babel.)

I realize that this isn't guaranteed to produce a defined result, due to the potential key collision. In my application I am preventing this elsewhere.

I'm actually using an OrderedMap, if that makes a difference.

Cratch answered 29/8, 2016 at 4:21 Comment(3)
There is a map() function available facebook.github.io/immutable-js/docs/#/Map/mapHinckley
Hi Ben, the function passed to map is expected to return a new value. I'm looking for something that's expected to produce a new key/value pair, because I need to change both.Cratch
Good point, I clearly didn't the question properlyHinckley
C
9

The function I was looking for is mapEntries. Here's an example:

Immutable.fromJS({1: 2, 3: 4}).mapEntries(([k, v]) => [k*k, v*v*v]).toJS()
// { 1: 8, 9: 64 }

mapEntries takes a function that takes a key/value pair as an array, and should return the new key/value pair also as another array.

Cratch answered 29/8, 2016 at 20:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.