2016-12-15 28 views
2

我想從這個數組中刪除未定義的值: [undefined,「een」,「twee」,undefined]。集合是這樣一個對象:如何使用lodash從數組中刪除值?

{container:{id:1},container2:{id:2},container3:{pid:2}} 

這不起作用:

_.remove(_.map(collection,'id'),"undefined") 

我該怎麼辦呢?

+2

'undefined'和''undefined「'不是一回事。 '_.remove(_。map(collection,'id'),undefined);'工作。投票結束爲錯字。 – Amadan

+1

Waarom lodash,array.filter wedkt goed –

+0

'.filter'還刪除了其他不真實的值,例如'false'和'0' –

回答

1

嘗試_.without(_.map(collection, 'id'), undefined)

_.remove()返回刪除的項目。

+0

@ 4castle https://lodash.com/docs/4.17.2#without –

0

對於數組,你可以使用 _.compact([NaN, 1, 0, 2, null, 5, undefined, 4]) 刪除所有falsey值,這將產生[1, 2, 5, 4]

_.compact文檔

如果您的收藏是一個對象,你可以使用

_.pickBy({foo: 'bar', baz: undefined}, _.identity)

實現類似結果:{foo: 'bar'}

當然,如果您有更復雜的邏輯,您可以隨時使用任何其他功能而不是_.identity

我也建議您根據您的需要查看_.remove()

另外,一切都可以通過_.filter,_.map,_.reduce來實現。

祝你好運!