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

如何更简洁地从API返回的对象数组中提取指定键值数组?

提取对象数组中指定属性的简洁方法

嘿,刚好碰到过类似的场景!其实map本身就是处理这种“从数组元素里提取特定属性”需求的最优解,而且通过对象解构可以让它变得更简洁,几乎是一行搞定的事儿。

最简洁的实现方式

直接在map的回调里解构出contactType属性,省去写item.contactType的步骤:

// 假设你的原始数组叫 contacts
const contacts = [
  { "contactType" : "AUTHORISED_SIGNATORY", "contactTypeName" : "Authorised Signatory" },
  { "contactType" : "LEGAL_CONTACT", "contactTypeName" : "Legal Contact" },
  { "contactType" : "PRIMARY_CONTACT", "contactTypeName" : "Primary Contact" }
];

// 一行提取出目标数组
const contactTypes = contacts.map(({ contactType }) => contactType);

执行后contactTypes就是你想要的结果:

["AUTHORISED_SIGNATORY", "LEGAL_CONTACT", "PRIMARY_CONTACT"]

有没有其他方法?

理论上可以用reduce来实现,但代码会更长,可读性也不如map直观,比如:

const contactTypes = contacts.reduce((acc, { contactType }) => {
  acc.push(contactType);
  return acc;
}, []);

或者更紧凑的写法:

const contactTypes = contacts.reduce((acc, { contactType }) => [...acc, contactType], []);

但这种写法完全没必要——map就是为这种“转换数组元素”的场景设计的,既简洁又语义明确,是首选方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:34:45