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

TypeScript中如何将对象集合转换为对应属性值组成的数组?

实现TypeScript对象数组提取字段值生成目标一维数组

使用数组原生map方法即可完成转换,不需要引入额外依赖。

基础实现代码

// 源数据
var data = [{"phrase": "hello"},{"phrase": "world"}];
// 遍历提取每个对象的phrase字段值
data = data.map(item => item.phrase);
// 转换后data的值为 ["hello","world"]

补充说明

  • map方法会遍历数组每一项,执行传入的回调逻辑后,返回由所有回调返回值组成的新数组,不会修改原数组内对象的结构
  • 如果需要开启TypeScript严格类型校验,可以补充对应类型定义,避免非法字段访问报错:
interface DataItem {
  phrase: string;
}
var data: DataItem[] = [{"phrase": "hello"},{"phrase": "world"}];
const result: string[] = data.map(item => item.phrase);
  • 如果源数据中可能存在缺失phrase字段的项,可以加容错逻辑,避免返回结果出现undefined:
const result = data.map(item => item?.phrase ?? '');

内容的提问来源于stack exchange,提问作者Sowndhar Kumar R

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 03:09:41