10

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!

1
  • 1
    I wanted to avoid fatigue :P Commented Aug 1, 2016 at 17:31

3 Answers 3

20

_.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>

Sign up to request clarification or add additional context in comments.

1 Comment

That wasn't clear in the docs! Was trying to combine with filter to no success
7

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

var result = _.reject(rooms, { channel: 'room-a', name: 'test' });

Comments

3
require('lodash')()

Calling the lodash function (by ()) creates a LoDash object that wraps undefined.

That's not what you want; you want the lodash function itself, which contains static methods.

Remove that.

2 Comments

uoooWoww impressive, I do not have much knowledge, but it was just a detail! so I thought well with my code, it worked like a charm! thankyou @SLaks !!!!
For more details about LoDash wrapper objects (for chaining), see their docs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.