簡體   English   中英

根據第二個數組中對象的屬性填充對象數組中缺失的對象

[英]Fill missing objects in an array of objects based on the property of an object in a second array

下面的代碼為三個類別(Class、Workshop、Training)之一添加一個收入 = 0 的對象元素,如果它們在那個月丟失(因此需要評估每個元素的類別月份屬性的組合)

const rawdata = [
  { category: 'Class', month: '2018-12-01T00:00:00.000Z', revenue: 100 },
  { category: 'Workshop', month: '2018-12-01T00:00:00.000Z', revenue: 140 },
  { category: 'Training', month: '2018-12-01T00:00:00.000Z', revenue: 300 },
  { category: 'Class', month: '2019-01-01T00:00:00.000Z', revenue: 200 },
  { category: 'Workshop', month: '2019-01-01T00:00:00.000Z', revenue: 200 },
  { category: 'Class', month: '2019-02-01T00:00:00.000Z', revenue: 134 },
  { category: 'Workshop', month: '2019-02-01T00:00:00.000Z', revenue: 124 },
  ...
];
const categories = Array.from(new Set(rawdata.map(x => x.category)));
const months = Array.from(new Set(rawdata.map(x => x.month)));
for(const month of months) {
  for(const category of categories) {
    const found = rawdata.find(element => element.month == month && element.category == category);
    if(!found) rawdata.push({ month, category, revenue: 0 });
  }
}

這將上面的數組更改為(注意帶有收入的元素:0):

[
  { category: 'Class', month: '2018-12-01T00:00:00.000Z', revenue: 100 },
  { category: 'Workshop', month: '2018-12-01T00:00:00.000Z', revenue: 140 },
  { category: 'Training', month: '2018-12-01T00:00:00.000Z', revenue: 300 },
  { category: 'Class', month: '2019-01-01T00:00:00.000Z', revenue: 200 },
  { category: 'Workshop', month: '2019-01-01T00:00:00.000Z', revenue: 200 },
  // Next object element was added
  { category: 'Training', month: '2019-01-01T00:00:00.000Z', revenue: 0 }
  { category: 'Class', month: '2019-02-01T00:00:00.000Z', revenue: 134 },
  { category: 'Workshop', month: '2019-02-01T00:00:00.000Z', revenue: 124 },
  // Next object element was added
  { category: 'Training', month: '2019-02-01T00:00:00.000Z', revenue: 0 }
  ...
];

有沒有更優雅的方法? 我正在做的事情有效,但似乎效率不高。

嘗試這個:

myArray.forEach(element=>{
    if(!element.revenue){
        element.revenue = 0
   }
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM