使用不同数组中的项目创建数组

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

我需要创建一个新的对象数组,其中包含 12 个项目(月份和值),但它必须检查其他数组中是否存在该月份。如果存在,它将推入数组,如果不存在,则值为 0

要检查的数组

arr1 = 
[
 {
   date: 2024-02,
   value: "100" 
 },
 {
   date: 2024-08,
   person: "200" 
 },
]

我做了什么

 const getMonthlyAmount = () => {
    let arr = [];

    for (i = 1; i <= 12; i++) {
      arr1.map((item) => {
        if (arr1.date.slice(0, 5) === i) {
          arr.push(item);
        }
      });
    }
    return arr;
  };

我想要的结果:

arr = [
 {
   date: 2024-01,
   value: 0
 }, 

 {
   date: 2024-02,
   value: "100" 
 },

... continue

 {
   date: 2024-08,
   person: "200" 
 },

... continue

 {
   date: 2024-12,
   value: 0 
 },
]
javascript
1个回答
0
投票

你可以这样做:

const getMonthlyAmount = () => {
  return Array.from({ length: 12 }, (_, i) => {
    const month = (i + 1).toString().padStart(2, '0');
    const date = `2024-${month}`;

    const foundItem = arr1.find((entry) => entry.date === date);
    
    return foundItem ? foundItem : { date, value: 0 };
  });
};

这将创建“缺失”月份,如果您提供的原始数组中不存在该月份,则将该值设置为 0。

演示

const arr1 = [
  {
    date: "2024-02",
    value: "100"
  },
  {
    date: "2024-08",
    person: "200"
  },
];

const getMonthlyAmount = () => {
  return Array.from({ length: 12 }, (_, i) => {
    const month = (i + 1).toString().padStart(2, '0');
    const date = `2024-${month}`;

    const foundItem = arr1.find((entry) => entry.date === date);
    
    return foundItem ? foundItem : { date, value: 0 };
  });
};

console.log(getMonthlyAmount());

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