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?
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}]
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
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/
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