TypeScript数组映射优化:如何保留原元素并实现属性重命名?
map Great question! Let's break down how to get the best of both worlds—clean destructuring syntax plus retaining all original object properties—without modifying your source data unnecessarily.
First, let's clarify the gap between your two approaches:
- Your first method modifies the original objects in the
resarray (adding/overwritingidanditemName) before returning them. This has hidden side effects, since it alters the source data. - Your second method creates a clean new object but only includes the renamed
idanditemNamefields, dropping all other properties from the original objects.
Recommended Approach (No Side Effects)
Use object destructuring with the spread operator (...) to preserve all original properties while renaming the ones you need. This returns entirely new objects, keeping your source data intact:
this.itemsList = res.map(({ code, name, ...rest }) => ({ ...rest, id: code, itemName: name }));
How This Works:
- Destructure & Capture Rest: We extract
codeandnamefrom each object, then use the rest operator (...rest) to collect every other original property into a single object. - Merge & Rename: We create a new object by first spreading all properties from
rest(keeping all original fields exceptcodeandname), then add the renamedidanditemNamefields with their values. - No Side Effects: Unlike your original approach, this doesn't touch the objects in the
resarray—safer for avoiding unexpected data changes elsewhere in your code.
If You Must Modify Original Objects (Not Recommended)
If you specifically need to update the original objects (like your first method), you can still clean up the code with destructuring:
this.itemsList = res.map(x => { const { code, name } = x; x.id = code; x.itemName = name; return x; });
Note: Modifying source data can lead to hard-to-debug issues, so the first approach is almost always the better choice.
Why Your Second Approach Didn't Work
Your original optimized snippet only returned id and itemName because you explicitly defined the new object to include only those two fields. The spread operator lets you retain all other properties while overwriting the ones you need to rename.
内容的提问来源于stack exchange,提问作者firasKoubaa

