按年份将多个Json对象存储在一个Json对象组中(javascript)

c3frrgcw  于 2023-01-10  发布在  Java
关注(0)|答案(1)|浏览(157)

我有 Json ·奥布耶克

{
  "2021": {
    "A177": { "Cost": 8828, "year": 2021 },
    "A276": { "Cost": 77538, "year": 2021 },
    "A188": { "Cost": 8082, "year": 2021 },
  },
  "2022": {
    "A2769": { "Cost": 3916, "year": 2022 },
    "A1779": { "Cost": 829, "year": 2022 },
    "A2709": { "Cost": 240, "year": 2022 },
  }
}

我希望:

[
  { "date": '2021', "A177": 8828, "A276": 77538, "A188": 8082},
  { "date": '2022', "A2769": 3916, "A1779": 829, "A2709": 240},
];

我该怎么做呢?
谢谢你的帮助

gpfsuwkq

gpfsuwkq1#

你可以遍历所有数据的键(即年份),然后创建一个对象,在date属性中包含年份以及年份数据的键。

const data = ...;

let finalized = Object.keys(data).map(k => {
    let yearsData = {}; // this is a year's worth of data
    for(let l of Object.keys(data[k]))
        yearsData[l] = data[k][l]['Cost']; // fill in costs
    yearsData['date'] = k; // fill in the date
    return yearsData;
});

console.log(finalized);

相关问题