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

如何在Angular 2中重组JSON,将Content数组内容移至主结构?

在Angular中转换错误数据结构的方法

需求回顾

先明确我们要完成的转换目标:把原始数据中每个条目里的Content数组展开,将数组内的每个对象与父级的Error字段合并,最终得到一个平铺的数组。

原始数据:

const err = [
  { "Error": "Name Not Valid", "Content": [ { "Name": "Johnz" } ] },
  { "Error": "Data Not Valid", "Content": [ { "Investor": "3785388", "ManagedBy": "Johnz" }, { "Investor": "1111111", "ManagedBy": "Mary" } ] }
]

目标结构:

const err= [
  { "Error": "Name Not Valid", "Name": "Johnz" },
  { "Error": "Data Not Valid", "Investor": "3785388", "ManagedBy": "Johnz" },
  { "Error": "Data Not Valid", "Investor": "1111111", "ManagedBy": "Mary" }
]

实现方法

在Angular中,你可以直接用原生JavaScript的数组方法完成这个转换,不需要额外依赖。最便捷的是用flatMap(先映射元素再扁平化结果)结合对象展开运算符...来合并字段:

const originalErr = [
  { "Error": "Name Not Valid", "Content": [ { "Name": "Johnz" } ] },
  { "Error": "Data Not Valid", "Content": [ { "Investor": "3785388", "ManagedBy": "Johnz" }, { "Investor": "1111111", "ManagedBy": "Mary" } ] }
];

const transformedErr = originalErr.flatMap(item => {
  // 遍历当前条目的Content数组,把每个对象和Error字段合并
  return item.Content.map(contentObj => ({
    Error: item.Error,
    ...contentObj
  }));
});

// 输出结果就是目标结构
console.log(transformedErr);

代码逻辑说明

  • flatMap:遍历原始数组的每个条目,对每个条目执行内部的map操作后,自动将所有子数组合并成一个大数组,完美匹配我们展开Content的需求。
  • 对象展开运算符...:把contentObj里的所有键值对合并到新对象中,同时保留父级的Error字段,避免手动逐个赋值。

兼容老环境的替代写法

如果你的项目需要兼容不支持ES2019的环境,可以用map结合concat来实现相同效果:

const transformedErr = [].concat(...originalErr.map(item => 
  item.Content.map(contentObj => ({
    Error: item.Error,
    ...contentObj
  }))
));

这个写法先通过map生成包含多个子数组的数组,再用concat把所有子数组拼接成一个平铺数组,逻辑和flatMap完全一致。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:28:12