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

TypeScript如何提取对象内数组属性拆分为多个同结构对象

TypeScript 对象结构转换实现

核心转换逻辑:遍历源对象的property数组,为数组中的每个值生成一个携带相同公共字段(此处为id)、property为当前遍历值的新对象,最终将所有新对象组合为数组返回。

基础实现

针对当前给定的结构,直接用数组map方法即可完成转换,TS 类型和代码如下:

// 源数据结构类型
type SourceType = {
  id: number;
  property: number[];
};
// 目标数据结构类型
type TargetType = {
  id: number;
  property: number;
};

const source: SourceType = { id: 1, property: [2, 3] };

// 执行转换
const target: TargetType[] = source.property.map((singleProp) => ({
  id: source.id,
  property: singleProp,
}));

// 输出结果与目标一致:[ { id: 1, property: 2 }, { id: 1, property: 3 } ]

通用封装方案

如果后续有同类拆分需求,可以抽成通用工具函数,自动推导类型,避免重复写逻辑:

/**
 * 按对象内的数组字段拆分对象为对象数组
 * @param source 待拆分的源对象
 * @param arrayField 要拆分的数组字段名
 * @returns 拆分后的对象数组
 */
function splitObjectByArrayField<
  T extends Record<string, unknown>,
  K extends keyof T
>(source: T, arrayField: K) {
  const fieldValue = source[arrayField];
  if (!Array.isArray(fieldValue)) {
    throw new Error(`指定字段 ${String(arrayField)} 不是数组类型,无法拆分`);
  }

  return fieldValue.map((singleItem) => ({
    ...source,
    [arrayField]: singleItem,
  })) as Omit<T, K> & Record<K, T[K] extends Array<infer ItemType> ? ItemType : never>[];
}

// 调用示例,结果类型自动推导为 {id: number, property: number}[]
const result = splitObjectByArrayField({ id: 1, property: [2, 3] }, 'property');

注意事项

  • 如果源对象除id、property外还有其他固定公共字段,优先用...source展开运算符先拷贝所有顶层字段,再覆盖property的值,避免手动漏写字段
  • 展开运算符为浅拷贝,如果源对象内存在其他引用类型值,后续修改新对象的引用字段会影响源对象和其他拆分结果,需要深拷贝的场景请额外处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 23:01:39