首页 > 解决方案 > 如果任何键为假,则过滤对象数组

问题描述

我怎样才能过滤这样的数组

[
    { foo: NaN, test: 'String' },
    { foo: 2, test: '' },
    { foo: 3, test: 'Something' },
]

并返回一个没有对象的新数组,其中键的值是虚假的?在这种情况下,应该只返回带有第三个对象的数组。

[
    { foo: 3, test: 'Something' },
]

标签: javascriptarraysfilter

解决方案


只需过滤并检查对象的所有值。

var array = [{ foo: NaN, test: 'String' }, { foo: 2, test: '' }, { foo: 3, test: 'Something' }],
    result = array.filter(o => Object.values(o).every(Boolean));

console.log(result);


推荐阅读