Skip to content

How can I remove an element from a list, with lodash?

I have an object that looks like this:

var obj = {
    "objectiveDetailId": 285,
    "objectiveId": 29,
    "number": 1,
    "text": "x",
    "subTopics": [{
        "subTopicId": 1,
        "number": 1
    }, {
        "subTopicId": 2,
        "number": 32
    }, {
        "subTopicId": 3,
        "number": 22
var stToDelete = 2;

I have lodash installed in my application for other things. Is there an efficient way to use lodash to delete the entry: {"subTopicId":2, "number":32} from the obj object?

Or is there a javascript way to do this?



As lyyons pointed out in the comments, more idiomatic and lodashy way to do this would be to use _.remove, like this

_.remove(obj.subTopics, {
    subTopicId: stToDelete

Apart from that, you can pass a predicate function whose result will be used to determine if the current element has to be removed or not.

_.remove(obj.subTopics, function(currentObject) {
    return currentObject.subTopicId === stToDelete;

Alternatively, you can create a new array by filtering the old one with _.filter and assign it to the same object, like this

obj.subTopics = _.filter(obj.subTopics, function(currentObject) {
    return currentObject.subTopicId !== stToDelete;


obj.subTopics = _.filter(obj.subTopics, {subTopicId: stToKeep});