Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove object from array, with Lodash?

I'm trying to remove an object from an array using Lodash.

In server.js (using NodeJS):

    var lodash = require('lodash')();

    var rooms = [
      { channel: 'room-a', name: 'test' },
      { channel: 'room-b', name: 'test' } 
    ]

I tried with two commands and it did not work:

    var result = lodash.find(rooms, {channel: 'room-a', name:'test'});
    var result = lodash.pull(rooms, lodash.find(rooms, {channel: 'room-a', name:'test'}));

Here's the output of console.log(result):

    LodashWrapper {
      __wrapped__: undefined,
      __actions__: [ { func: [Function], args: [Object], thisArg: [Object] } ],
      __chain__: false,
      __index__: 0,
      __values__: undefined }

Can someone help me? Thank you!

like image 764
Fábio Zangirolami Avatar asked Aug 01 '16 17:08

Fábio Zangirolami


People also ask

How do I remove an object from an array using Lodash?

remove() Method. The _. remove() method is used to remove all elements from the array that predicate returns True and returns the removed elements.

How do you remove an object from an array of objects?

To remove an object from an array, use the array. pop() method. The array. pop() function deletes the last element and returns that element.

How do I remove a property from an array of objects?

To remove a property from all objects in an array:Use the Array. forEach() method to iterate over the array. On each iteration, use the delete operator to delete the specific property. The property will get removed from all objects in the array.

How do I remove a property from object Lodash?

unset() method is used to remove the property at the path of the object. If the property is removed then it returns True value otherwise, it returns False.


2 Answers

_.remove() is a good option.

var rooms = [
  { channel: 'room-a', name: 'test' },
  { channel: 'room-b', name: 'test' } 
];

_.remove(rooms, {channel: 'room-b'});

console.log(rooms); //[{"channel": "room-a", "name": "test"}]
<script src="https://cdn.jsdelivr.net/lodash/4.14.2/lodash.min.js"></script>
like image 172
Stanislav Ostapenko Avatar answered Oct 26 '22 23:10

Stanislav Ostapenko


I'd go for reject() in this scenario. Less code:

var result = _.reject(rooms, { channel: 'room-a', name: 'test' });
like image 22
Adam Boduch Avatar answered Oct 26 '22 23:10

Adam Boduch