【发布时间】:2017-04-12 14:04:11
【问题描述】:
我编写了一个代码,成功地将数组 (called: "wishlistArray") 插入到现有的
对象使用数组 push() 函数。
正如您已经猜到的那样,当用户想要将项目添加到他/她的愿望清单时触发。
为了清楚起见,请在我的对象架构下方查找,这表明用户 ID 为:"udEnfEmy5DSBvDsSy" 已经将该对象添加到他/她的“愿望清单”中
_id: "DFhcAYAtMBviczogo"
createdDate: "04/12/2017"
expiryDate: "04/22/2017"
noOfViews: 125
wishListArray: Array[1]
0: Object
wishedBy: "udEnfEmy5DSBvDsSy"
为避免在 wishlistArray 数组中插入重复项,我检查当前用户 ID 是否已存在于 wishlistArray 数组中,如下所示:
var selectedItemIDSet = Session.get('selectedItemIDSet');
var addToWishList = buyList.find(selectedItemIDSet);
var currentUser = [Meteor.user()._id ];
var wheatherWishListedOrNot = buyList.find({ _id:selectedID, 'wishListArray.wishedBy': {$in: currentUser } } ).count();
addToWishList.forEach(function(itemName){
var currentObjectID = itemName._id;
//### If wishListArrayArray array already exists in then...
if (itemName.wishListArray) {
var wishListArray = [,...itemName.wishListArray];
//### If current user hasnt wish listed item then add to Wish List (wishListArray) array
if (wheatherWishListedOrNot == "0") {
wishListArray.push({ wishedBy: Meteor.user()._id });
Session.set('wishListArrayToGo',wishListArray );
}
else if(wheatherWishListedOrNot == "1") {
//### Else if WishedListed by current user, Do absolutely nothing!
}
}
var wishListArray = Session.get('wishListArrayToGo');
buyList.update(currentObjectID, {$set: {wishListArray: wishListArray} });
});
解释了我是如何做到这一点的,但我在做相反的事情时遇到了问题?如何从 wishListArray 数组中删除用户?
我尝试了下面的代码,但没有成功。
var selectedItemIDSet = Session.get('selectedItemIDSet');
var removeFromWishList = buyList.find(selectedItemIDSet);
var currentUser = [Meteor.user()._id ];
wheatherWishListedOrNot = buyList.find({ _id:selectedID, 'wishListArray.wishedBy': {$in: currentUser } } ).count();
removeFromWishList.forEach(function(itemName){
var currentObjectID = itemName._id;
//### If wishListArrayArray array already exists in then...
if (itemName.wishListArray) {
var wishListArray = [,...itemName.wishListArray];
//### If current user current user is on **WishedListArray**, then remove from **WishedListArray** array.
if (wheatherWishListedOrNot == "1") {
wishListArray.splice({ wishedBy: Meteor.user()._id });
Session.set('wishListArrayToGo',wishListArray );
}
else if(wheatherWishListedOrNot == "0") {
//### Else if current user isnt on WishedListArray, Do absolutely nothing!
}
}
var wishListArray = Session.get('wishListArrayToGo');
buyList.update(currentObjectID, {$set: {wishListArray: wishListArray} });
});
我尝试删除的代码对我来说似乎是合乎逻辑的,但未能从 WishlistArray 中删除用户 ID。有人可以指出我哪里出错了吗?
提前致谢!
【问题讨论】:
标签: javascript arrays meteor associative-array splice