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

Angular 14数组数据格式转换求助:合并数组项重构属性

Angular 14 数组转换实现方案

核心思路

利用数组的reduce方法遍历原始数组,逐步构建目标对象:

  • 保留每个元素的parentItem和childItem属性(假设所有元素的这两个属性值一致,若不一致会以最后一个元素的值为准)
  • 将每个元素的columnName作为属性名,对应oldValue为属性值
  • 新增${columnName}_newValue格式的属性,存储对应的newValue

代码实现

基础版本(TypeScript)

const originalArray = [
  {
    "parentItem": "WBP258R",
    "childItem": "WBP258R",
    "columnName": "Color",
    "oldValue": "Rainbow",
    "newValue": "Rainbow1"
  },
  {
    "parentItem": "WBP258R",
    "childItem": "WBP258R",
    "columnName": "Pg #",
    "oldValue": "4",
    "newValue": "44"
  },
  {
    "parentItem": "WBP258R",
    "childItem": "WBP258R",
    "columnName": "Status",
    "oldValue": "New",
    "newValue": "Rev"
  }
];

const transformedObject = originalArray.reduce((acc, current) => {
  // 赋值公共属性
  acc.parentItem = current.parentItem;
  acc.childItem = current.childItem;
  // 处理当前列的旧值与新值
  acc[current.columnName] = current.oldValue;
  acc[`${current.columnName}_newValue`] = current.newValue;
  return acc;
}, {} as Record<string, any>);

// 输出结果与需求一致
console.log(transformedObject);

类型安全版本

为了符合Angular的TypeScript最佳实践,可定义接口约束数据类型:

// 原始数据结构接口
interface OriginalItem {
  parentItem: string;
  childItem: string;
  columnName: string;
  oldValue: string;
  newValue: string;
}

// 转换后对象的类型(动态属性用索引签名)
interface TransformedResult {
  parentItem: string;
  childItem: string;
  [key: string]: string;
}

const originalArray: OriginalItem[] = [/* 原始数据 */];

// 处理空数组的边界情况
if (originalArray.length === 0) {
  console.log('原始数组为空');
}

const transformedObject: TransformedResult = originalArray.reduce((acc, current) => {
  acc.parentItem = current.parentItem;
  acc.childItem = current.childItem;
  acc[current.columnName] = current.oldValue;
  acc[`${current.columnName}_newValue`] = current.newValue;
  return acc;
}, {} as TransformedResult);

注意事项

  • 如果原始数组中存在不同的parentItem或childItem,转换后的对象会以最后一个元素的这两个属性值为准;若需要处理这种场景,可先按parentItem+childItem分组再转换
  • 若columnName存在重复值,后出现的元素会覆盖之前的属性值,需根据业务需求判断是否需要去重或合并

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 19:12:47