簡體   English   中英

根據過濾數據創建新對象

[英]Create new object based on filtered data

我需要幫助。 我需要計算當年每個月的用戶操作量。 我有一系列日期:

let years = ['2017', '2018', '2019']
let datesArray = [
    {date: "2019-06-05", userActionsAmount: 88},
    {date: "2019-06-04", userActionsAmount: 314}
]

我有計數對象

let counts = {}

然后我像這樣迭代:

years.forEach(year => {
          counts[year] = datesArray.filter(singleDay => singleDay.date.slice(0, -6) === year).reduce((acc, obj) => {
            return acc + obj.userActionsAmount
          }, 0)
        })

使用此代碼計數結果是: {2017: 0, 2018: 0, 2019: 402}沒關系,但我需要將日期分成幾個月,所以我需要這樣的東西:

{ 2017: []},
{ 2018: []}
{ 2019: [
  { '01': 0 },
  { '02': 0 },
  { '03': 0 },
  { '04': 0 },
  { '05': 0 },
  { '06': 402 },
  { '07': 0 },
  { '08': 0 },
  { '09': 0 },
  { '10': 0 },
  { '11': 0 },
  { '12': 0 }
]}

你可以這樣做:

 let datesArray = [ {date: "2019-06-05", userActionsAmount: 88}, {date: "2019-06-04", userActionsAmount: 314} ] let result={}; datesArray.forEach(dateItem=>{ let date=dateItem.date.split("-"); let year=date[0]; let month=date[1]; if(!result[year]) result[year]={}; if(!result[year][month]) result[year][month]=0; result[year][month]+=dateItem.userActionsAmount; })

您可以在需要時創建屬性。 這里有兩種解決方案:一種使用數組方法,第二種更明確。

初始化:

const monthsKeys = ["01", "02", "03","04", "05", "06", "07", "08", "09", "10", "11", "12"];
const years = ['2017', '2018', '2019'];
const datesArray = [
    {date: "2019-06-05", userActionsAmount: 88},
    {date: "2019-06-04", userActionsAmount: 314}
];
const counts = {};

解決方案1:

years.forEach( y => { counts[y] = []; });
datesArray.forEach(dateCount => { 
    const [year, month, day] = dateCount.date.split("-");
    if (counts[year].length === 0) monthsKeys.forEach(m => {counts[year].push({[m] : 0});});
    counts[year][Number(month) - 1][month] += dateCount.userActionsAmount;
});
console.log(counts);

解決方案2:

// fill counts with years
for (const y of years) {
    counts[y] = [];
}

// fill counts with months and count
for (const e of datesArray) {
    const splittedDate = e.date.split("-");
    const year = splittedDate[0];
    const month = splittedDate[1];

    // create year if needed, not necessary if years array is sure
    if ( ! year in counts) {
        counts[year] = [];
    }

    // create monthes if needed
    if (counts[year].length === 0) {
        for (const m of monthsKeys) {
             counts[year].push({[m]: 0});
        }  
    }

    // add value
    counts[year][Number(month) - 1][month] += e.userActionsAmount;
}
console.log(counts)

為什么是年份值(月數)的對象數組而不是簡單的對象?

這基本上是一個非常簡單的分組

 const datesArray = [ {date: "2019-06-05", userActionsAmount: 88}, {date: "2019-06-04", userActionsAmount: 314} ]; const groupedByMonth = datesArray.reduce((a, b) => a.set(b.date.substring(0,7), ~~a.get(b.date.substring(0,7)) + b.userActionsAmount), new Map); console.log([...groupedByMonth]);

要使其符合您的格式,您可以執行以下操作

const yourFormat = years.map(e => ({
  [e]: Array.from(groupedByMonth).filter(([k, v]) => k.substring(0,4) === e).map(([k, v]) => ({[k.substring(5,7)]: v}))
})); 

然后

該解決方案與 OP 的預期輸出有所不同,但我認為它應該符合 OP 的要求。 如果沒有,這是根據需要獲得輸出的一個步驟......

 const years = [2017, 2018, 2019] const dates = [{ date: "2019-06-05", userActionAmount: 88 }, { date: "2019-06-04", userActionAmount: 314 } ] const transform = (years, dates) => dates.reduce( (output, { date, userActionAmount, parsedDate = new Date(date), year = parsedDate.getFullYear(), month = parsedDate.getMonth() + 1, yearData = output[year] }) => (yearData[month] += userActionAmount) && output, Object.fromEntries(years.map(year => [year, Object.fromEntries(Array.from({ length: 12 }, (_, x) => [x + 1, 0]))]))) const output = transform(years, dates) console.log(output) // This output lets you get total amount // of some given month in the following way: const monthAmount = output[2019][6] console.log (monthAmount)

暫無
暫無

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

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