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

如何将JavaScript数组对象转换为仅含id字段的新数组?

解决方案:用map()快速提取id字段

嘿,这事儿其实用你试过的map()方法就能完美解决!你之前可能没找对正确的写法,我给你一步步演示:

首先看你的原数组:

var pilots = [
  { id: 2, name: "Wedge Antilles", faction: "Rebels" },
  { id: 8, name: "Ciena Ree", faction: "Empire" },
  { id: 40, name: "Iden Versio", faction: "Empire" },
  { id: 66, name: "Thane Kyrell", faction: "Rebels" }
];

我们只需要用map()遍历每个元素,返回一个仅包含id属性的新对象就行:

const idOnlyPilots = pilots.map(pilot => ({ id: pilot.id }));

执行这段代码后,idOnlyPilots就是你想要的结果:

[ { id: 2 }, { id: 8 }, { id: 40 }, { id: 66 } ]

小提示

这里要注意箭头函数返回对象时,必须用括号()把对象包起来——不然JavaScript会把大括号{}当成函数体的分隔符,而不是对象字面量,这点很容易踩坑!

额外:用reduce()实现的方式

如果你好奇用reduce()怎么写,也可以参考下面的代码(不过map()在这个场景下更简洁直观):

const idOnlyPilotsReduce = pilots.reduce((acc, pilot) => {
  acc.push({ id: pilot.id });
  return acc;
}, []);

内容的提问来源于stack exchange,提问作者user12205142

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 10:07:45