Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete an object in an array in lodash

I have an array of objects and I need to delete few of the objects based on conditions. How can I achieve it using lodash map function? Ex:

[{a: 1}, {a: 0}, {a: 9}, {a: -1}, {a: 'string'}, {a: 5}]

I need to delete

{a: 0}, {a: -1}, {a: 'string'}

How can I achieve it?

like image 311
Pradeep Rajashekar Avatar asked Nov 22 '17 05:11

Pradeep Rajashekar


3 Answers

You can use lodash's remove function to achieve this. It transforms the array in place and return the elements that have been removed

var array = [{a: 1}, {a: 0}, {a: 9}, {a: 5}];
var removed = _.remove(array, item => item.a === 0);

console.log(array);
// => [{a: 1}, {a: 9}, {a: 5}]

console.log(removed);
// => [{a: 0}]
like image 137
klugjo Avatar answered Oct 01 '22 04:10

klugjo


ES6

const arr = [{a: 1}, {a: 0}, {a: 9}, {a: 5}];

const newArr = _.filter(arr, ({a}) => a !== 0);

ES5

var arr = [{a: 1}, {a: 0}, {a: 9}, {a: 5}];

var newArr = _.filter(arr, function(item) { return item.a !== 0 });

https://lodash.com/docs/4.17.4#filter

like image 42
Joey Avatar answered Oct 01 '22 03:10

Joey


Other then _.remove or _.filter you can also use reject()

var array = [{a: 1}, {a: 0}, {a: 9}, {a: 5}];
var result = _.reject(array , ({a}) => a===0 });

console.log(result);//[{a: 1}, {a: 9}, {a: 5}]

https://jsfiddle.net/7z5n5ure/

like image 35
Emad Dehnavi Avatar answered Oct 01 '22 03:10

Emad Dehnavi