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:
我有一个对象数组,我需要根据条件删除一些对象。如何使用lodash map函数实现?例:
[{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?
我怎样才能做到呢?
4 个解决方案
#1
3
You can use lodash's remove function to achieve this. It transforms the array in place and return the elements that have been removed
您可以使用lodash的删除功能来实现这一点。它将数组转换到适当的位置并返回已删除的元素
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}]
#2
1
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过滤器
#3
0
Other then _.remove or _.filter you can also use reject()
其他然后_。删除或_。也可以使用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/
#4
-1
use this pass arr, key on which you want condition to apply and value is value of key you want to check.
使用此pass arr,您希望条件应用的关键字和值是您想要检查的键值。
function removeElem(arr,key,value){
return arr.filter(elem=>elem[key]===value)
}
#1
3
You can use lodash's remove function to achieve this. It transforms the array in place and return the elements that have been removed
您可以使用lodash的删除功能来实现这一点。它将数组转换到适当的位置并返回已删除的元素
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}]
#2
1
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过滤器
#3
0
Other then _.remove or _.filter you can also use reject()
其他然后_。删除或_。也可以使用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/
#4
-1
use this pass arr, key on which you want condition to apply and value is value of key you want to check.
使用此pass arr,您希望条件应用的关键字和值是您想要检查的键值。
function removeElem(arr,key,value){
return arr.filter(elem=>elem[key]===value)
}