简体   繁体   English

如何从.map()JS创建不可变的映射

[英]How to create an immutable map from .map() JS

So I have a function like this 所以我有这样的功能

myNewMap = oldMap.map((check) => {
     if (check.get('_id') === against.get('_id')) return check;
});

The only problem is myNewMap is the same size as the oldMap (which makes sense), but is there a way to stop this, or do I need a different approach? 唯一的问题是myNewMap与oldMap的大小相同(这是有道理的),但是有没有办法阻止它,或者我需要一个不同的方法?

I think you want filter 我想你想要filter

myNewMap = oldMap.filter((check) => {
   return check.get('_id') === against.get('_id');
});

Or even shorter: 甚至更短:

myNewMap = oldMap.filter(check => check.get('_id') === against.get('_id'));

This will return a new Map with only the values that meet the predicate. 这将返回一个仅包含符合谓词的值的新Map

After you map over the array you can do 映射数组后,您可以执行此操作

Object.seal( yourMappedArrayObject );

That will make that object then immutable. 这将使该对象变得不可变。

Object.seal Object.seal

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM