Search code examples
javascriptangularfirebaselodash

Issue in removing object using Lodash _remove


I am having an Object:

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

If I Iterate using .map function of lodash

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

it gives me value of each id.

Now when I am trying to remove it using _remove it is not working as expected.

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

Still there is no difference in ids Object.

I am really new to angular4 and using lodash for the first time. I just wanted to remove a value from ids object and get the remaining object.

Print of console.

enter image description here I am using firebase and trying to delete data after retrieving it from 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)
        });
      }
  }

Solution

  • You want _filter instead

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