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
Immutable.js Map values to array
提问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 sr
is an Array
of Object
, so if you use .fromJS
to convert it, it becomes List
of Map
.
这是因为sr
是一个Array
of Object
,所以如果你.fromJS
用来转换它,它就变成List
了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
.
的is.valueSeq().toArray();
(valueSeq
在这里没有必要。)把它转换成Array
的Map
,所以你通过数组需要循环,每个转换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()]