[英]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?
如何使用lodash map函数实现它? 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. 您可以使用lodash的remove函数来实现此目的。 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 ES6
const arr = [{a: 1}, {a: 0}, {a: 9}, {a: 5}];
const newArr = _.filter(arr, ({a}) => a !== 0);
ES5 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 https://lodash.com/docs/4.17.4#filter
Other then _.remove or _.filter you can also use reject() 除了_.remove或_.filter之外你还可以使用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/ https://jsfiddle.net/7z5n5ure/
use this pass arr, key on which you want condition to apply and value is value of key you want to check. 使用此pass arr,您要应用条件的键,value是您要检查的键的值。
function removeElem(arr,key,value){
return arr.filter(elem=>elem[key]===value)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.