我有一个数组,可以在查看/查看时收集图像的统计信息。读取数组时,它会显示捕获的信息,例如用户查看的日期,以及特定用户_id(由{viewedDate: "Sat Apr 08 2017 23:00:47", viewedBy: "udEnfEmy5DSBvDsSy"}
{viewedDate: "Sat Apr 08 2017 23:01:17", viewedBy: "udEnfEmy5DSBvDsSy"}
{viewedDate: "Sat Apr 08 2017 23:01:27", viewedBy: "udEnfEmy5DSBvDsSy"}
{viewedDate: "Sat Apr 08 2017 23:02:37", viewedBy: "udEnfEmy5DSBvDsSy"}
生成)。如下所示:
viewedBy
您注意到viewedBy
字段中存在重复项。如何避免 var viewStatistics = buyList.find({_id:"kegqdvFHFoQptvJXn"});
var currentUserID = Meteor.user()._id;
viewStatistics.forEach(function(itemName){
viewStatisticsArray = [,...itemName.viewStatisticsArray];
if (viewStatisticsArray.indexOf(itemName)== -1) viewStatisticsArray.push({viewedDate: Date(), viewedBy: Meteor.user()._id });
});
字段中的重复项?
在下面查找我当前的代码:
viewedBy
在尝试避免输入重复项if (viewStatisticsArray.indexOf(itemName.viewedBy)== -1) viewStatisticsArray.push({viewedDate: Date(), viewedBy: Meteor.user()._id });
失败的情况下,我还尝试了下面的代码,这些代码在逻辑上有很多意义,但未能达到预期的效果:
{{1}}
非常感谢任何帮助!
答案 0 :(得分:0)
viewStatisticsArray.indexOf()== -1无法正常工作,因为数组的每个元素都不同(日期不同)。
你可以这样做:
var viewedByItem = viewStatisticsArray.filter(function(d) {
return d.viewedBy == itemName.viewedBy;
});
if (viewedByItem.length == 0) {
viewStatisticsArray.push({viewedDate: Date(), viewedBy: Meteor.user()._id });
}
或者如果你仍想使用indexOf(),你可以创建一个map函数来返回每个对象的seenBy属性:
var viewedByPeople = viewStatisticsArray.map(function(d) {
return d.viewedBy;
}
if (viewedByPeople.indexOf(itemName.viewedBy) == -1) {
viewStatisticsArray.push({viewedDate: Date(), viewedBy: Meteor.user()._id });
}