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!
remove() Method. The _. remove() method is used to remove all elements from the array that predicate returns True and returns the removed elements.
To remove an object from an array, use the array. pop() method. The array. pop() function deletes the last element and returns that element.
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.
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.
_.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>
I'd go for reject() in this scenario. Less code:
var result = _.reject(rooms, { channel: 'room-a', name: 'test' });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With