簡體   English   中英

如何在lodash中刪除數組中的對象

[英]How to delete an object in an array in lodash

我有一個對象數組,我需要根據條件刪除一些對象。 如何使用lodash map函數實現它? 例如:

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

我需要刪除

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

我怎樣才能實現它?

您可以使用lodash的remove函數來實現此目的。 它將數組轉換到適當位置並返回已刪除的元素

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

除了_.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/

使用此pass arr,您要應用條件的鍵,value是您要檢查的鍵的值。

function removeElem(arr,key,value){
    return arr.filter(elem=>elem[key]===value)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM