如何在forEach中为Immutable Map内的Immutable List添加元素?
Add Required Strings to All Immutable Map Categories
To solve this problem, we need to ensure every category in your Immutable Map contains all the required strings. Since Immutable.js data structures are immutable (can't be changed in place), we'll create a new updated Map instead of modifying the original. Here's a clean, idiomatic solution:
Complete Solution Code
import { Map, List } from 'immutable'; // Your original categories map const categories = new Map({ cat1: new List(['animal', 'color']), cat2: new List(['animal']), }); // Define the strings every category MUST include const requiredStrings = ['animal', 'color']; // Can be a regular array or Immutable List // Generate the updated categories map const updatedCategories = categories.map((currentList) => { // Iterate through required strings and add any missing ones to the list return requiredStrings.reduce((updatedList, requiredStr) => { // Only add the string if it's not already present return updatedList.includes(requiredStr) ? updatedList : updatedList.push(requiredStr); }, currentList); }); // Verify the result (convert to plain JS for readability) console.log(updatedCategories.toJS()); // Output: { cat1: ['animal', 'color'], cat2: ['animal', 'color'] }
Key Explanations
- Immutable Operations: We use
categories.map()to create a new Map (instead of mutating the original). This is the standard approach for updating Immutable collections. - Reduce to Add Missing Strings: For each category's List,
reduce()iterates over the required strings. If a string isn't already in the list, we usepush()(which returns a new List, since Immutable doesn't allow mutation) to add it. - Avoid Duplicates: The
includes()check ensures we don't add duplicate strings even if they're already present in the original list.
Why Your Partial Approach Might Not Work
Your initial code uses forEach(), which doesn't return a new collection. Since Immutable objects can't be mutated, modifying them inside forEach() won't change the original Map. Using map() is more efficient and aligns with Immutable.js best practices.
内容的提问来源于stack exchange,提问作者jamesvphan
相关产品推荐
相关产品推荐

