2016-12-15 297 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来实现。

祝你好运!