如何在 javascript 中用 0 值填充给定年份的缺失月份?

问题描述 投票:0回答:1

数据:

const data = [
  {time: "2020-10-13", value: 3},   
  {time: "2020-11-13", value: 30},  
  {time: "2021-01-13", value: 12}, 
  {time: "2021-02-13", value: 1},   
  {time: "2021-03-13", value: 23},   
  {time: "2021-04-13", value: 10}, ...
]

我将此数据格式化为以下格式:[数字,数字,数字] [] --> [月,年,值]

对于示例数据,它将是:

[[11, 2020, 3], [10, 2020, 30], [1, 2021, 12], [2, 2021, 1], ...]

当月份缺失时,如何添加值 0 和月份?例如,2020 年少了 10 个月,2021 年少了 9 个月。我想添加它,看起来像这样:

[[1, 2020, 0], [2, 2020, 0],[3, 2020, 0], [4 2020, 0],[5, 2020, 30, [6, 2020, 0],[7, 2020, 0],[8, 2020, 0],[9, 2020, 0], [10, 2020, 30],[11, 2020, 3], [10, 2020, 30], [1, 2021, 12], [2, 2021, 1], ...]

最好的方法是什么?

谢谢!!

编辑:

我尝试过的一些代码:

const months =[1,2,3,4,5,6,7,8,9,10,11,12];
const res = data.flatMap(({time,value}) => {
  const [y,m,d] = time.split("-").map(Number); 
  const res = months.map((month, i) => {
    if (m === month) {
      return [m, y, value]
    } else {
      return [month, y, 0]
    }
  })
  return res;
})
const changeData = (data) => {
    let res = {};
     data.forEach((item) => {
       const {time, value} = item;
       const [y,m,d] = time.split("-").map(Number);
       res[y] !== undefined ? res[y].push({m, value})
       : res[y] = [{m, value}];
    })
    return res;
}
const newData = changeData(data);
console.log(newData)
const months =[1,2,3,4,5,6,7,8,9,10,11,12];

const formatData = () => {
    let result = [];
    for (const [key, value] of Object.entries(newData)) {
        value.slice(0, 12).map((val, i) => {
            const y = key;
            const {m, value} = val;
            const res = months.map((month, i) => {
    
            if (m === month) {
                result.push([m, y, value]);
            } else {
              result.push([month, y, 0]);
            }
        })
        })     
    }
    return result;
}
javascript
1个回答
0
投票

您应该循环遍历时间范围,而不是

newData
字典中的条目。对于每个月,检查它是否出现在
newData
中。如果该值存在,则使用该值,否则默认为 0。

const changeData = (data) => {
    let res = {};
     data.forEach((item) => {
       const {time, value} = item;
       const [y,m,d] = time.split("-").map(Number);
       res[y] !== undefined ? res[y].push({m, value})
       : res[y] = [{m, value}];
    })
    return res;
}
const newData = changeData(data);

const formatData = () => {
  let result = [];
  for (let year = 2020; year < 2022; year++) {
    for (let month = 1; month <= 12; month++) {
      result.push([year, month, newData?.[year]?.[month]?.value || 0]);
    }
  }
  return result;
}
console.log(formatData());
<script>
const data = [
  {time: "2020-10-13", value: 3},   
  {time: "2020-11-13", value: 30},  
  {time: "2021-01-13", value: 12}, 
  {time: "2021-02-13", value: 1},   
  {time: "2021-03-13", value: 23},   
  {time: "2021-04-13", value: 10}
]
</script>

© www.soinside.com 2019 - 2024. All rights reserved.