【问题标题】:Issue in removing object using Lodash _remove使用 Lodash _remove 删除对象的问题
【发布时间】:2018-10-24 09:15:15
【问题描述】:

我有一个对象:

ids = [ "-LIof_e0hPtXKtkc4Uh9", "-LIjBcGO7m7VQ-B3pfYt" ]

如果我使用lodash.map 函数进行迭代

_.map(ids, (userID, key) => {
     console.log('Lopping userId',userID);
})

它给了我每个 id 的价值。

现在,当我尝试使用 _remove 删除它时,它没有按预期工作。

_.remove(ids, (value, key, obj) => value == idToBeRemoved);

ids 对象仍然没有区别。

我对 angular4 非常陌生,并且是第一次使用 lodash。 我只是想从ids 对象中删除一个值并获取剩余的对象。

控制台打印。

我正在使用 firebase 并在从 firebase 检索数据后尝试删除数据:

deleteTransactWith(transactWithKey,transactWithUser) {
    let currentUser = this._authService.getLoggedInUser();
    console.log(transactWithUser.groups)
    console.log(Object.keys(transactWithUser.groups).length)
    console.log('key To remove',transactWithKey)
    for (var key in transactWithUser.groups) {
      if (transactWithUser.groups.hasOwnProperty(key)) {
        let group = this.firebase.object(`/url/${currentUser.$key}/${key}`);
        group.snapshotChanges().take(1).subscribe((groupData: any) => {
          groupData = groupData.payload.toJSON();
          //console.log('not removed',groupData.userIds)
          console.log('key',transactWithKey)
          _.remove(groupData.userIds, (value) => value == transactWithKey);
          //_.pull(groupData.userIds, transactWithKey);
          console.log('removed',groupData.userIds)
        });
      }
  }

【问题讨论】:

  • 你的map函数是做什么的?
  • 没什么。我只是想检查键和值
  • “我有一个对象:”——不,你没有,你有一个数组
  • 你有一个元素数组
  • 我附上了控制台的图片

标签: javascript angular firebase lodash


【解决方案1】:

你想要_filter

const ids = [ "-LIof_e0hPtXKtkc4Uh9", "-LIjBcGO7m7VQ-B3pfYt" ]
const idToBeRemoved = "-LIof_e0hPtXKtkc4Uh9"
const filteredIds = _.filter(ids, function(id) { return id !== idToBeRemoved})
console.log(filteredIds)

【讨论】:

  • 更新答案。
  • 我在我的问题中添加了一个代码。请检查我从 Firebase 获取数据的最后一个函数。您能否根据此提供您的答案
  • 谢谢你的工作。你能解释一下为什么 _remove 甚至 _pull 都不起作用
  • 在路上。我会在今晚晚些时候
  • _.remove & _.pull 类似。他们从源数组中删除元素并返回它们。 _.remove 接受一个函数进行比较; _.pull 需要一个值列表来比较 _.filter 使用一个函数来匹配项目并返回除匹配项目之外的所有项目。不更改源集合。使用什么取决于您是否要更改原始数组、是否需要匹配项或除匹配项之外的所有内容。
【解决方案2】:

你可以简单地使用 lodash _.pull

const _ = require("lodash");
const ids = [ "-LIof_e0hPtXKtkc4Uh9", "-LIjBcGO7m7VQ-B3pfYt" ]
const result = _.pull(ids, "-LIjBcGO7m7VQ-B3pfYt" )
console.log(filteredIds)

【讨论】:

    【解决方案3】:

    首先找到你要删除的项目的索引,然后通过_.pullAt(lodash)从中拉出

        let getIndex= _.findIndex(this.images, function(o) { return o.name == img.name; });
        let removedImage = _.pullAt(this.images, getIndex) ;
    

    【讨论】:

      猜你喜欢
      • 2016-01-03
      • 2017-03-12
      • 2014-07-18
      • 1970-01-01
      • 2011-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多