Javascript Immutable.js 将值映射到数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33148796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:42:21  来源:igfitidea点击:

Immutable.js Map values to array

javascriptimmutable.js

提问by LenW

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

我正在使用来自http://facebook.github.io/immutable-js/docs/#/Map的不可变 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()

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/

看到这个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 ?

我们从不可变数据结构中得到的数组似乎仍然装饰着每个包含对象的不可变字段。这是意料之中的吗?

采纳答案by fuyushimoya

It's because the sris an Arrayof Object, so if you use .fromJSto convert it, it becomes Listof Map.

这是因为sr是一个Arrayof Object,所以如果你.fromJS用来转换它,它就变成ListMap

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

is.valueSeq().toArray();valueSeq在这里没有必要。)把它转换成ArrayMap,所以你通过数组需要循环,每个转换Map项目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>

回答by Hüseyin Zengin

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

someMap.toIndexedSeq().toArray()用于获取仅包含值的数组。

回答by ericsoco

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).

Map.values()返回一个 ES6 Iterable(如 doMap.keys()Map.entries()),因此您可以使用Array.from()展开运算符转换为数组(如本答案中所述)。

e.g.:

例如:

Array.from(map.values())

Array.from(map.values())

or just

要不就

[...map.values()]

[...map.values()]