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

如何将宽格式JavaScript对象数组转换为React-table适用的长格式

如何将宽格式的对象数组转换为长格式

输入数组

[
  {
    series: "opening_balance",
    "Oct 2021": 12713238.3,
    "Nov 2021": 27713238.3,
    "Dec 2021": 22713238.3,
  },
  {
    series: "inflow",
    "Oct 2021": 7,
    "Nov 2021": 40000000,
    "Dec 2021": 50000000,
  }
];

期望输出数组

[
  { year_month: "Oct 2021", opening_balance: 5, inflow: 100 },
  { year_month: "Nov 2021", opening_balance: 10, inflow: 200 },
  { year_month: "Dec 2021", opening_balance: 15, inflow: 150 },
];

背景说明:上述输出原本是API接口返回的原始数据,此前为了适配React-table使用被转换为宽格式,功能运行正常。但当前表格单元格已支持编辑,需要在另一个组件中更新源数据,因此需要将现有宽格式数据转换回原始长格式。

错误实现与问题

原有错误代码:

let data = [
  {
    series: "opening_balance",
    "Oct 2021": 5,
    "Nov 2021": 10,
    "Dec 2021": 15,
  },
  {
    series: "inflow",
    "Oct 2021": 100,
    "Nov 2021": 200,
    "Dec 2021": 150,
  },
];

let results = data.map((row) => {
  let keys = Object.keys(row);

  let x = keys.map((key) => {
    return { year_month: key, value: row[key] };
  });
  return [...x];
});

console.log("results:", results);

原有代码输出:

results: [
  [
    { year_month: 'series', value: 'opening_balance' },
    { year_month: 'Oct 2021', value: 5 },
    { year_month: 'Nov 2021', value: 10 },
    { year_month: 'Dec 2021', value: 15 }
  ],
  [
    { year_month: 'series', value: 'inflow' },
    { year_month: 'Oct 2021', value: 100 },
    { year_month: 'Nov 2021', value: 200 },
    { year_month: 'Dec 2021', value: 150 }
  ]
]

问题原因:没有过滤series字段,也没有将相同月份的不同指标值合并到同一个对象中,最终得到嵌套的二维数组,不符合要求。

正确实现代码

const data = [
  {
    series: "opening_balance",
    "Oct 2021": 5,
    "Nov 2021": 10,
    "Dec 2021": 15,
  },
  {
    series: "inflow",
    "Oct 2021": 100,
    "Nov 2021": 200,
    "Dec 2021": 150,
  },
];

// 提取所有月份字段,排除series字段
const monthList = Object.keys(data[0]).filter(key => key !== 'series');

// 按月份遍历组装数据
const transformResult = monthList.map(month => {
  const record = { year_month: month };
  data.forEach(item => {
    record[item.series] = item[month];
  });
  return record;
});

console.log(transformResult);

运行结果

[
  { year_month: "Oct 2021", opening_balance: 5, inflow: 100 },
  { year_month: "Nov 2021", opening_balance: 10, inflow: 200 },
  { year_month: "Dec 2021", opening_balance: 15, inflow: 150 },
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 07:09:04