我有一个对象
var obj = [
{
key1: true,
},
{
key1: true,
key2: true,
},
{
key1: true,
key2: false,
}
]
我的过滤器功能是
const result = obj.filter(item => (!("key2" in item) || item.key2) );
return result;
在这里,我尝试使用key2
不存在或key2
为true来过滤数组项。但是我得到的是完整的项目,它不是用key2: false
var obj = [{
key1: true,
},
{
key1: true,
key2: true,
},
{
key1: true,
key2: false,
}
]
const result = obj.filter(item => (!("key2" in item) || item.key2));
console.log(result);
预期结果
var obj = [
{
key1: true,
},
{
key1: true,
key2: true,
},
]
答案 0 :(得分:1)
var obj = [
{
key1: true,
},
{
key1: true,
key2: true,
},
{
key1: true,
key2: false,
}
]
obj.filter(item => (!item.hasOwnProperty('key2') || item.key2));
答案 1 :(得分:0)
使用Object.hasOwnProperty('key2')
在对象中查找密钥
var obj = [
{
key1: true,
},
{
key1: true,
key2: true,
},
{
key1: true,
key2: false,
}
]
const result = obj.filter(item => (!item.hasOwnProperty('key2') || item.key2) );
console.log(result);
答案 2 :(得分:0)
您还可以过滤undefined
:
var data = [ { key1: true, }, { key1: true, key2: true, }, { key1: true, key2: false, } ]
let result = data.filter(({key2}) => key2 === undefined || key2)
console.log(result)
这将过滤key2为truthy
或undefined
或更短,如Aswin
所建议:
var data = [ { key1: true, }, { key1: true, key2: true, }, { key1: true, key2: false, } ]
let result = data.filter(({key2}) => !key2)
console.log(result)