You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript数组映射优化:如何保留原元素并实现属性重命名?

Solution: Keep All Original Properties While Renaming Specific Fields in 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 res array (adding/overwriting id and itemName) 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 id and itemName fields, dropping all other properties from the original objects.

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:

  1. Destructure & Capture Rest: We extract code and name from each object, then use the rest operator (...rest) to collect every other original property into a single object.
  2. Merge & Rename: We create a new object by first spreading all properties from rest (keeping all original fields except code and name), then add the renamed id and itemName fields with their values.
  3. No Side Effects: Unlike your original approach, this doesn't touch the objects in the res array—safer for avoiding unexpected data changes elsewhere in your code.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:12:24