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

如何重构JSON对象:将日期键转为单日期对象结构

重构动态日期的JSON数组

现有JSON数组中,每个对象以日期作为键,包含education字段表示教育类型,对应不同日期的数值。需要重构JSON,使每个对象仅对应一个日期,将日期值单独提取为date字段,同时将该日期下各教育类型的数值作为对象属性。由于日期是动态可变的,无法硬编码处理。

当前数据格式及代码

var arr = [{
  "education": "school",
  "2021-12": 65.45,
  "2022-01": 172762.27,
  "2022-02": "959.5"
}, {
  "education": "colleg",
  "2021-12": 270.13,
  "2022-01": 105429534.09,
  "2022-02": 53543770.9,
  "2022-03": 100004545
}, {
  "education": "university",
  "2021-12": 168396.95,
  "2022-01": 170417648.96999997,
  "2022-02": 1202822.9
}];

let result = [];
arr.forEach((element, index) => {
  let subObj = {}
  let keys = Object.keys(element);
  for (var propt in element) {
    if (keys.indexOf(propt) > -1) {
      if (element.hasOwnProperty('2021-12')) {
        subObj['education'] = element[propt]
      }
    }
  }
  result.push(subObj)
});

console.log(result);

期望输出格式

[{
  "school": "65.45",
  "colleg": "270.13",
  "university": "168396.95",
  "date": "2021-12"
}, {
  "school": "172762.27",
  "colleg": "105429534.09",
  "university": "170417648.96999997",
  "date": "2022-01"
}, {
  "school": "959.5",
  "colleg": "53543770.9",
  "university": "1202822.9",
  "date": "2022-02"
}, {
  "colleg": "100004545",
  "date": "2022-03"
}]

解决方案

要实现动态日期的重构,核心思路是先收集所有唯一日期,再针对每个日期聚合对应教育类型的数据:

var arr = [{
  "education": "school",
  "2021-12": 65.45,
  "2022-01": 172762.27,
  "2022-02": "959.5"
}, {
  "education": "colleg",
  "2021-12": 270.13,
  "2022-01": 105429534.09,
  "2022-02": 53543770.9,
  "2022-03": 100004545
}, {
  "education": "university",
  "2021-12": 168396.95,
  "2022-01": 170417648.96999997,
  "2022-02": 1202822.9
}];

// 收集所有唯一日期(过滤掉education字段)
const allDates = [...new Set(arr.flatMap(item => Object.keys(item).filter(key => key !== 'education')))];

// 遍历每个日期,构建对应的结果对象
const result = allDates.map(date => {
  const dateItem = { date };
  arr.forEach(eduItem => {
    // 如果当前教育条目包含该日期,添加对应键值对
    if (eduItem.hasOwnProperty(date)) {
      dateItem[eduItem.education] = String(eduItem[date]);
    }
  });
  return dateItem;
});

console.log(result);

代码说明

  1. 收集日期:通过flatMap遍历所有条目,提取非education的键(即日期),再用Set去重得到所有唯一日期,完全适配动态场景;
  2. 构建结果对象:针对每个日期初始化包含date字段的对象,再遍历每个教育条目,若条目存在当前日期的数据,就将教育类型作为键、对应值转成字符串(匹配期望输出格式)存入对象;
  3. 输出结果:最终数组完全符合目标格式,无需硬编码任何日期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 23:24:55