javascript - 从对象数组中删除元素

标签 javascript mongodb meteor indexof

我正在使用 Meteor 构建一个实时通知系统,但由于我以前从未这样做过,所以我肯定会想办法得到一些有用的东西。

我有一个<ul>通知列表。我定义了一个单击 <a class="notif-link"> 的事件每个 <li>包含。

我的通知有 ID、类型和一些我们不关心的其他内容。

notifications:
    [
         {id: 0, type: 0, img: null, link: "/profile"},
         {id: 1, type: 1, img: null, link: "/profile"},
         {id: 2, type: 2, img: null, link: "/profile"},
         {id: 3, type: 3, img: null, link: "/profile"},
    ]

...

Template.navigation.events({
       "click .notif-link": function(e, tmpl){
           console.log(EJSON.stringify(this)); // print the verbosed notification object as shown above
           var index = Meteor.user().profile.notifications.indexOf({id: this.id});
           console.log(index); // always == -1
           newNotifArray = Meteor.user().profile.notifications.splice(index, 1);
           Meteor.users.update({_id: Meteor.userId()}, {$set: {'profile.notifications': newNotifArray}});
       }
   });

notification.id设置为<a> #id ,这应该允许我识别数组中的通知并在单击链接时将其删除。

问题是 notification.indexOf({id : this.id})总是给我返回-1。 我想问题是我不知道如何在对象数组上正确工作。

有人可以向我解释一下如何处理吗?

谢谢你。

最佳答案

问题是您试图查找您创建的新对象的索引:{id: this.id} ,在您定义的通知对象数组中,显然不包括它。

Array.IndexOf当给定一个要搜索的对象时,将尝试在数组中查找相同的对象(内存中的指针),因此除非您拥有实际的对象,否则您无法真正使用它。 例如:notifications.indexOf({id: 0, type: 0, img: null, link: "/profile"}) ,也会返回 -1,因为它是一个不同的对象,即使具有相同的值。

我不熟悉 Meteor,但是有一些库可以在这种情况下为您提供帮助,例如下划线对于数组和列表助手非常有帮助。 对于这种情况,您可以使用下划线的 findWhere方法如下:

_.notifications.findWhere({id: this.id})

这将返回数组中与您指定的属性匹配的实际对象,然后您可以使用该实际对象 Array.indexOf获取数组中对象的索引。

我确信还有很多其他方法和库可以做到这一点,具体取决于您已经使用的内容。 以下是一些不使用下划线的其他解决方案的链接:

使用纯Javascript map - indexOf method in an object array?

使用 JQuery grep - Find object by id in an array of JavaScript objects

干杯。

关于javascript - 从对象数组中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29877254/

相关文章:

javascript - 在不使用 jquery 的情况下在 Meteor 中动态添加文本字段

javascript - 我如何定位这个特定的进度标签?

javascript - 在 3D 模型上画一条与其表面相符的线

node.js - 如何在数组mongodb中推送新字段

javascript - react 变量定义时未定义

javascript - Meteorjs实现无限滚动,先显示最新数据

javascript - 如何使 superfish 下拉菜单响应?

javascript - 打印 JavaScript 时出现问题

python - 如何使用 MongoEngine 将 MySQL 数据库转移到 MongoDB?

arrays - 如何知道我的数据库数组中存在哪个数组元素?