在Immutable.js中如何合并两个集合并让新值覆盖旧值?
staticProp Hey there! The problem with Set.union() here is that it operates on reference equality for objects and doesn't handle the specific overwrite logic you need—it just adds new entries that aren't already in the set. Since your original and update objects are separate references, Set.union() would keep both instead of replacing the old changingProp value.
Instead, you'll want to build a custom merge function that matches objects by their staticProp key and replaces the entry when a match is found. Here are a couple of straightforward approaches:
Approach 1: Using Map for Full Control
This method lets you both overwrite existing entries and add new ones from the update array (if needed):
const original = [ { staticProp: "something", changingProp: [ '1', '2' ] }, { staticProp: "somethingElse", changingProp: [] } ]; const updates = [{ staticProp: "something", changingProp: [ '3' ] }]; const mergeByStaticProp = (originalArr, updateArr) => { // Create a map from the original array, using staticProp as the key const mergedMap = new Map(originalArr.map(item => [item.staticProp, {...item}])); // Apply updates: overwrite existing entries or add new ones updateArr.forEach(update => { mergedMap.set(update.staticProp, {...update}); }); // Convert the map back to an array return Array.from(mergedMap.values()); }; const result = mergeByStaticProp(original, updates); console.log(result); // Output: [ // { staticProp: "something", changingProp: [ '3' ] }, // { staticProp: "somethingElse", changingProp: [] } // ]
Approach 2: Simplified map + Map (For Overwriting Only)
If you don't need to add new entries from the update array and just want to overwrite existing ones in the original, this shorter version works:
const mergeByStaticProp = (originalArr, updateArr) => { const updateLookup = new Map(updateArr.map(item => [item.staticProp, item])); // Map over original array: use update if exists, else keep original return originalArr.map(item => updateLookup.get(item.staticProp) || item); };
How It Works
Both approaches use staticProp as the unique identifier to match objects:
- The
Mapstructure lets you quickly look up and replace entries by their key. - We spread objects (
{...item}) to avoid mutating the original arrays—this keeps your data immutable, which is a good practice in most cases.
This gives you exactly the behavior you want: replacing the changingProp for matching staticProp values, while keeping all other original entries intact.
内容的提问来源于stack exchange,提问作者Wassap124

