如何在对象映射中插入条件语句?



这个问题的后续:

如何在具有重复属性名称的对象中获取最大属性值?

如果当前迭代等于一年,我想插入条件语句

我尝试这样做:

var monthlyHighest = Array.from(
getMonthlyValues.reduce(
(m, {month, subs, year}) => {
if(year == 2018){ //here is the conditional statement
return m.set(month, Math.max(m.get(month) || 0, subs))
}
},new Map),
([month, subs, year]) => ({ month, subs, year}));

但是我收到"无法将未定义或 null 转换为对象">错误,在我的理解中,如果行 if(year == 2018(返回 false,则整个 reduce 函数将不再继续。

我使用以下数组进行测试:

1: {month: "2018-07-24", subs: 2}
2: {month: "2018-07-31", subs: 3}
3: {month: "2019-08-01", subs: 2}
4: {month: "2019-08-02", subs: 3}
5: {month: "2019-08-05", subs: 3}
6: {month: "2019-08-08", subs: 4}
7: {month: "2019-08-14", subs: 5}
8: {month: "2019-08-20", subs: 7}
9: {month: "2019-08-23", subs: 7}
10: {month: "2019-08-28", subs: 8}
11: {month: "2019-08-29", subs: 11}
12: {month: "2019-09-02", subs: 2}
13: {month: "2019-09-03", subs: 2}
14: {month: "2019-09-04", subs: 3}
15: {month: "2019-09-05", subs: 5}
16: {month: "2019-09-06", subs: 5}
17: {month: "2019-09-09", subs: 6}
18: {month: "2019-09-10", subs: 7}
19: {month: "2019-09-11", subs: 8}
20: {month: "2019-09-12", subs: 9}

我认为您实际使用的数据具有对象{year, month, subs}其中月份只是月份?

这有效:注意硬编码的年份

([month, subs, year]) => ({ month, subs, year:2018})

因为 Map 在Array.from使用的可迭代对象中只有 2 个元素 - 不确定您预计这一年来自哪里

const getMonthlyValues = [,
{month: "2018-07-24", subs: 2},
{month: "2018-07-31", subs: 3},
{month: "2019-08-01", subs: 2},
{month: "2019-08-02", subs: 3},
{month: "2019-08-05", subs: 3},
{month: "2019-08-08", subs: 4},
{month: "2019-08-14", subs: 5},
{month: "2019-08-20", subs: 7},
{month: "2019-08-23", subs: 7},
{month: "2019-08-28", subs: 8},
{month: "2019-08-29", subs: 11},
{month: "2019-09-02", subs: 2},
{month: "2019-09-03", subs: 2},
{month: "2019-09-04", subs: 3},
{month: "2019-09-05", subs: 5},
{month: "2019-09-06", subs: 5},
{month: "2019-09-09", subs: 6},
{month: "2019-09-10", subs: 7},
{month: "2019-09-11", subs: 8},
{month: "2019-09-12", subs: 9},
].map(v => ({year: v.month.split('-')[0], month: v.month.split('-')[1], subs:v.subs}));
var monthlyHighest = Array.from(
getMonthlyValues.reduce((m, {month, subs, year}) => {
if(year == 2018){ //here is the conditional statement
m.set(month, Math.max(m.get(month) || 0, subs))
}
return m;
}, new Map),
([month, subs, year]) => ({ month, subs, year:2018})
);
console.log(monthlyHighest);

相关内容

  • 没有找到相关文章

最新更新