对具有相同键的javascript对象值求和
如果日期相同,我会尝试添加喜欢的数量。根据我的代码,我有相同的日期,但不同的时间一天。我想加上那天所有喜欢的东西。这是日期数组对象对具有相同键的javascript对象值求和,javascript,arrays,sorting,datetime,object,Javascript,Arrays,Sorting,Datetime,Object,如果日期相同,我会尝试添加喜欢的数量。根据我的代码,我有相同的日期,但不同的时间一天。我想加上那天所有喜欢的东西。这是日期数组对象 var date = [{text: "b", len: 1, Date: "Fri May 01 2020 10:49:01 GMT+0100 (West Africa Standard Time)", Source: "Twitter for Android", Likes: 1}, {text: "b", len: 1, Date: "Fri May 01
var date = [{text: "b", len: 1, Date: "Fri May 01 2020 10:49:01 GMT+0100 (West Africa Standard
Time)", Source: "Twitter for Android", Likes: 1},
{text: "b", len: 1, Date: "Fri May 01 2020 10:50:03 GMT+0100 (West Africa Standard Time)", Likes: 1},
{text: "b", len: 1, Date: "Fri May 02 2020 10:55:03 GMT+0100 (West Africa Standard Time)",Likes: 4},
{text: "b", len: 1, Date: "Fri May 02 2020 10:56:03 GMT+0100 (West Africa Standard Time)",Likes: 3},
{text: "b they will neither comment not like this tweet", len: 47, Date: "Fri May 01 2020 11:35:49
GMT+0100 (West Africa Standard Time)", Likes: 0}]
我想要
`[{Date: May 01 2020, Likes:3}, {Date: May 02 2020, Likes:7}]`
您可以使用下面的代码生成所需的结果
const makeDateString = dateString => {
const date = new Date(dateString);
return date.toLocaleString("default", {
year: "numeric",
month: "long",
day: "numeric"
});
};
const resultObject = date.reduce((likes, item) => {
const newDateString = makeDateString(item.Date);
if (likes[newDateString]) {
likes[newDateString] = likes[newDateString] + item.Likes;
} else {
likes[newDateString] = item.Likes;
}
return likes;
}, {});
const result = Object.entries(resultObject).map(item => {
return {
Date: item[0],
Likes: item[1]
};
});
使用moment和lodash,您可以通过以下代码实现这一点:
var moment = require('moment')
var _ = require('lodash')
var dates = [{text: "b", len: 1, Date: "Fri May 01 2020 10:49:01 GMT+0100 (West Africa Standard Time)", Source: "Twitter for Android", Likes: 1}, {text: "b", len: 1, Date: "Fri May 01 2020 10:50:03 GMT+0100 (West Africa Standard Time)", Likes: 1}, {text: "b", len: 1, Date: "Fri May 02 2020 10:55:03 GMT+0100 (West Africa Standard Time)",Likes: 4}, {text: "b", len: 1, Date: "Fri May 02 2020 10:56:03 GMT+0100 (West Africa Standard Time)",Likes: 3}, {text: "b they will neither comment not like this tweet", len: 47, Date: "Fri May 01 2020 11:35:49 GMT+0100 (West Africa Standard Time)", Likes: 0}];
var datesFormatted = dates.map(d => ({ date: moment(new Date(d.Date)).format("MMM DD YYYY"), likes: d.Likes }));
const result = _(datesFormatted)
.groupBy('date')
.map((dateValue, date) => ({
date: date,
likes: _.sumBy(dateValue, "likes")
}))
.value()
console.log(result)
结果如下:
[ { date: 'May 01 2020', likes: 2 },
{ date: 'May 02 2020', likes: 7 } ]
检查此链接是否有用:如果已将其签出,则解决方案是将同一日期分组。我正在尝试在我的date对象中添加所有喜欢的对象,如果它们具有相同的日期,您将必须实现类似的功能,按日期分组(丢弃时间值),然后对每个组的
喜欢数进行求和,这是您的结果。请告诉我,我的JS知识不是很强,谢谢。谢谢您的帮助,我已经实现了它,它很有效。太好了,谢谢!!