Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

immutable.js

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.

like image 234
Landon Kuhn Avatar asked Aug 29 '16 04:08

Landon Kuhn


People also ask

What is Immutable Map JavaScript?

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.

What is immutable map in react?

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>

Is map mutable in JS?

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.


1 Answers

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.

like image 181
Landon Kuhn Avatar answered Sep 27 '22 19:09

Landon Kuhn