Javascript检查过滤器方法中的键是否不存在或应具有特定值

时间:2019-05-24 06:21:42

标签: javascript arrays object

我有一个对象

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,
  },
]

3 个答案:

答案 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为truthyundefined

或更短,如Aswin所建议:

var data = [ { key1: true, }, { key1: true, key2: true, }, { key1: true, key2: false, } ] 

let result = data.filter(({key2}) => !key2)

console.log(result)