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.
An Immutable Map is an unordered collection of key-value pairs that are based on JavaScript's object. Let's create a very basic Map collection. 1import { Map } from "immutable"; 2 3const myMap = Map(); js. We import Map constructor from immutable , then call the constructor and assign it to a variable.
Immutable Map is an unordered Iterable. Keyed of (key, value) pairs with O(log32 N) gets and O(log32 N) persistent sets. type Map<K, V> extends Collection.Keyed<K, V>
The map() method returns an entirely new array with transformed elements and the same amount of data. In the case of forEach() , even if it returns undefined , it will mutate the original array with the callback . Therefore, we see clearly that map() relies on immutability and forEach() is a mutator method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With