问题
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 ?
回答1:
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>
回答2:
Just use someMap.toIndexedSeq().toArray()
for getting an array of only values.
回答3:
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()]
来源:https://stackoverflow.com/questions/33148796/immutable-js-map-values-to-array