簡體   English   中英

過濾掉具有空值的數組,下划線

[英]Filter out an array with null values, underscore

我有這個數組:

[null, {name:'John'}, null, {name:'Jane'}]

我想刪除空值。 使用下划線有一種簡單的方法嗎?

如果數組包含空值或對象,那么您可以使用compact

var everythingButTheNulls = _.compact(list);

NB compact刪除所有虛假值,因此如果數組可能包含零,false等,那么它們也將被刪除。

也可以使用帶有isNull謂詞的reject

var everythingButTheNulls = _.reject(array, _.isNull);

嘗試使用_.without(array, *values)它將刪除您不需要的所有值。 在你的情況下* values == null

http://underscorejs.org/#without

這對你有用

過濾

_.filter(arr,function (value) {
    return value!==null;
})

拒絕

_.reject(arr,function (value) {
    return value===null;
})

從下划線文檔

without_.without(array, *values) 
Returns a copy of the array with all instances of the values removed.

所以只需使用這種方法

var a = [null, {name:'John'}, null, {name:'Jane'}]
a = _.without(a, null);

暫無
暫無

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

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