使用对象“过滤”对象数组

时间:2018-01-13 18:32:36

标签: javascript

我有以下对象数组:

const users = [
    {name: "John", age: "20", houses:{mountain: true, beach: false, penthouse: true, countryhouse: false}},
    {name: "Paul", age: "32", houses:{mountain: false, beach: false, penthouse: true, countryhouse: true}},
    {name: "Michael", age: "53", houses:{mountain: true, beach: true, penthouse: false, countryhouse: false}}
]

以下

const properties = {mountain: true, beach: true, penthouse: false, countryhouse: false}

我要做的是使用对象属性过滤掉不符合条件的用户(当其中一个属性切换为true或多个属性时)。

我尝试了不同的混合结果的不同方法(包括使用属性对象中的键来创建一个只包含具有真正布尔值的键的单个对象)但是我确实得到了一些非常奇怪的结果,具体取决于方法。什么是最好的方式呢? 我想返回一个只包含对象属性

标准的对象数组

1 个答案:

答案 0 :(得分:1)

使用Array#filter迭代数组。在过滤器回调中,使用Array#keysArray#every来检查houses中的所有属性是否等于properties常量:



const users = [{name: "John", age: "20", houses:{mountain: true, beach: false, penthouse: true, countryhouse: false}},{name: "Paul", age: "32", houses:{mountain: false, beach: false, penthouse: true, countryhouse: true}},{name: "Michael", age: "53", houses:{mountain: true, beach: true, penthouse: false, countryhouse: false}}];

const properties = {mountain: true, beach: true, penthouse: false, countryhouse: false};

const result = users.filter(({ houses }) => 
  Object.keys(properties).every((key) => properties[key] === houses[key])
);

console.log(result);