[javascript] 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?

This question is related to javascript arrays object lodash

The answer is


you can do it with _pull.

_.pull(obj["subTopics"] , {"subTopicId":2, "number":32});

check the reference


You can now use _.reject which allows you to filter based on what you need to get rid of, instead of what you need to keep.

unlike _.pull or _.remove that only work on arrays, ._reject is working on any Collection

obj.subTopics = _.reject(obj.subTopics, (o) => {
  return o.number >= 32;
});

There are four ways to do this as I know

const array = [{id:1,name:'Jim'},{id:2,name:'Parker'}];
const toDelete = 1;

The first:

_.reject(array, {id:toDelete})

The second one is :

_.remove(array, {id:toDelete})

In this way the array will be mutated.

The third one is :

_.differenceBy(array,[{id:toDelete}],'id')
// If you can get remove item 
// _.differenceWith(array,[removeItem])

The last one is:

_.filter(array,({id})=>id!==toDelete)

I am learning lodash

Answer to make a record, so that I can find it later.


You can use removeItemFromArrayByPath function which includes some lodash functions and splice

/**
 * Remove item from array by given path and index
 *
 * Note: this function mutates array.
 *
 * @param {Object|Array} data (object or array)
 * @param {Array|String} The array path to remove given index
 * @param {Number} index to be removed from given data by path
 *
 * @returns {undefined}
 */

const removeItemFromArrayByPath = (data, arrayPath, indexToRemove) => {
  const array = _.get(data, arrayPath, []);
  if (!_.isEmpty(array)) {
    array.splice(indexToRemove, 1);
  }
};

You can check the examples here: https://codepen.io/fatihturgut/pen/NWbxLNv


In Addition to @thefourtheye answer, using predicate instead of traditional anonymous functions:

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

OR

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

lodash and typescript

const clearSubTopics = _.filter(obj.subTopics, topic => (!_.isEqual(topic.subTopicId, 2)));
console.log(clearSubTopics);

Just use vanilla JS. You can use splice to remove the element:

obj.subTopics.splice(1, 1);

Demo


Here is the simple lodash function with array and deleting it with the index number.

index_tobe_delete = 1

fruit = [{a: "apple"}, {b: "banana"}, {c: "choco"}]
_.filter(fruit, (value, key)=> {
return (key !== index_tobe_delete)
})

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to lodash

Can't perform a React state update on an unmounted component Angular 4 HttpClient Query Parameters use Lodash to sort array of object by value How to group an array of objects by key Removing object properties with Lodash How to merge two arrays of objects by ID using lodash? Error: EACCES: permission denied Replacing objects in array lodash: mapping array to object Correct way to import lodash