如何通过允许值集合筛选OrderedMap子集?相关方法疑问
deleteAll to filter an OrderedMap to keep only allowed keys? Yes, absolutely! While deleteAll is built to remove specified keys, you can use it indirectly to retain only your allowed values by deleting the inverse set of keys (those not in your allowed list). Here's how to implement this step-by-step:
Step 1: Identify keys to remove
First, you need to get all keys from your OrderedMap that are not in your allowed values array. Use keySeq() to get an iterable of the map's keys, then filter out the ones present in allowed:
const allowed = ['item1', 'item3']; const originalMap = OrderedMap({ item1: { key: 'sdfd', value:'sdfd' }, item2: { key: 'sdfd', value:'sdfd' }, item3: { key: 'sdfd', value:'sdfd' } }); // Extract keys that aren't in the allowed list const keysToDelete = originalMap.keySeq().filter(key => !allowed.includes(key));
Step 2: Apply deleteAll to remove unwanted keys
Pass the keysToDelete iterable to deleteAll. Since OrderedMap is immutable, this returns a new map with only your allowed keys retained:
const filteredOrderedMap = originalMap.deleteAll(keysToDelete); // Result: { item1: { key: 'sdfd', value:'sdfd' }, item3: { key: 'sdfd', value:'sdfd' } }
Key Notes
- Immutability: Remember that
deleteAlldoesn't modify the original OrderedMap—it returns a new instance. Always assign the result to a variable if you want to work with the filtered map. - Missing keys handling: If your
allowedarray contains keys that don't exist in the map,deleteAllwill simply ignore them (no errors will be thrown). - Performance tradeoffs: This approach shines when the number of keys to delete is smaller than the number to keep. If you're retaining only a handful of keys, using
filterdirectly might be more intuitive:// Alternative filter approach const filteredMap = originalMap.filter((value, key) => allowed.includes(key));
Why this works
deleteAll accepts any iterable of keys to remove. By generating the list of non-allowed keys, you're effectively telling it to strip away everything except your desired entries—this is a clever inverse use of the method that perfectly aligns with your goal.
内容的提问来源于stack exchange,提问作者Sanjay A

