LenW
LenW

Reputation: 3096

Immutable.js Map values to array

I am using the immutable Map from http://facebook.github.io/immutable-js/docs/#/Map

I need to get an array of the values out to pass to a backend service and I think I am missing something basic, how do I do it ?

I have tried :

mymap.valueSeq().toArray()

But I still get an immutable data structure back ?

For example :

var d = '[{"address":"10.0.35.118","cpus":4}]';
var sr = JSON.parse(d);
var is = Immutable.fromJS(sr);

console.log(sr);

console.log(is.toArray());
console.log(is.valueSeq().toArray());

See this http://jsfiddle.net/3sjq148f/2/

The array that we get back from the immutable data structure seems to still be adorned with the immutable fields for each contained object. Is that to be expected ?

Upvotes: 28

Views: 53279

Answers (3)

ericsoco
ericsoco

Reputation: 26253

Map.values() returns an ES6 Iterable (as do Map.keys() and Map.entries()), and therefore you can convert to an array with Array.from() or the spread operator (as described in this answer).

e.g.:

Array.from(map.values())

or just

[...map.values()]

Upvotes: 10

fuyushimoya
fuyushimoya

Reputation: 9813

It's because the sr is an Array of Object, so if you use .fromJS to convert it, it becomes List of Map.

The is.valueSeq().toArray();(valueSeq is not necessary here.) converts it to Array of Map, so you need to loop through the array, and convert each Map item to Array.

var d = '[{"address":"10.0.35.118","cpus":4}]';
var sr = JSON.parse(d);

// Array of Object => List of Map
var is = Immutable.fromJS(sr);

console.log(sr);
console.log(is.toArray());

// Now its Array of Map
var list = is.valueSeq().toArray();

console.log(list);

list.forEach(function(item) {
  
  // Convert Map to Array
  console.log(item.toArray());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.7.5/immutable.min.js"></script>

Upvotes: 23

H&#252;seyin Zengin
H&#252;seyin Zengin

Reputation: 1226

Just use someMap.toIndexedSeq().toArray() for getting an array of only values.

Upvotes: 26

Related Questions