我有一个对象数组,如下所示:
[
{
Daypart: "G_POSTPEAK",
day_of_week: "Monday",
uplift: 1
},
{
Daypart: "A_BREAKFAST",
day_of_week: "Thursday",
uplift: 1
},
{
Daypart: "C_DAYTIME",
day_of_week: "Sunday",
uplift: 2
},
{
Daypart: "G_POSTPEAK",
day_of_week: "Monday",
uplift: 2
},
]我只展示了数组中的一个对象样本,我正在处理更多的对象。它们都具有指定的属性,daypart属性可以是8个值中的一个,而星期的值可以是7(一周中的几天)中的一个。
我想返回具有相同daypart和day_of_week值的所有对象的提升值的总和。
因此,上面的代码应该返回如下内容:
{
G_POSTPEAK_Monday: {
Daypart: "G_POSTPEAK",
day_of_week: "Monday",
uplift: 3
},
A_BREAKFAST_Thursday: {
Daypart: "A_BREAKFAST",
day_of_week: "Thursday",
uplift: 1
},
C_DAYTIME_Sunday: {
Daypart: "C_DAYTIME",
day_of_week: "Sunday",
uplift: 2
}
}感谢任何帮助
发布于 2019-06-18 19:34:31
可以使用以下函数。我用过ES6。该函数以inputs作为输入对象。
const sumIt = (inputs) => {
const result = {};
inputs.forEach((input) => {
const key = `${input.Daypart}_${input.day_of_week}`;
if (key in result) {
result[key].uplift = result[key].uplift + input.uplift;
} else {
result[key] = { ...input };
}
});
return result;
};
发布于 2019-06-18 19:38:34
您可以使用ES6 reduce函数在一行中执行求和,而不是使用foreach。
let array = [
{
Daypart: "G_POSTPEAK",
day_of_week: "Monday",
uplift: 1
},
{
Daypart: "A_BREAKFAST",
day_of_week: "Thursday",
uplift: 1
},
{
Daypart: "C_DAYTIME",
day_of_week: "Sunday",
uplift: 2
},
{
Daypart: "G_POSTPEAK",
day_of_week: "Monday",
uplift: 2
},
];
const totalUplift = array.reduce((acc, array) => acc + array.uplift, 0);
console.log(totalUplift);
发布于 2019-06-18 19:53:45
可以使用array#reduce根据对象累加器中的Daypart和day_of_week对数据进行分组。
let data = [ { Daypart: "G_POSTPEAK", day_of_week: "Monday", uplift: 1 }, { Daypart: "A_BREAKFAST", day_of_week: "Thursday", uplift: 1 }, { Daypart: "C_DAYTIME", day_of_week: "Sunday", uplift: 2 }, { Daypart: "G_POSTPEAK", day_of_week: "Monday", uplift: 2 }],
result = data.reduce((r,o) => {
let key = `${o.Daypart}_${o.day_of_week}`;
r[key] = r[key] || {...o, uplift: 0};
r[key].uplift += o.uplift;
return r;
},{});
console.log(result);.as-console-wrapper {max-height: 100% !important; top: 0;}
https://stackoverflow.com/questions/56648029
复制相似问题