首页 > 解决方案 > 使用 ES6 使用属性值过滤数据

问题描述

喜欢根据对象的属性值过滤数据假设我有一个对象:

{
  A: { value1: 4, value2: 2, value3: 5 },
  B: { value1: 2, value2: 5, value3: 8 },
  ...
}

我想通过过滤上面的对象来创建对象,所以如果我过滤基于value1: 4 and value2: 2

{
  value1: 4,
  value2: 2,
  value3: 5
}

我正在寻找一种使用 Es6 完成此任务的干净方法。

标签: javascriptecmascript-6

解决方案


const 
  obj = { A: { value1: 4, value2: 2, value3: 5 }, B: { value1: 2, value2: 5, value3: 8 } },
  filter = { value1: 4, value2: 2 };

// get key-value pairs of filter  
const filterPairs = Object.entries(filter);
  
// iterate over obj's values, and return the ones matching filterPairs
const matches = 
  Object.values(obj)
  .filter(o => filterPairs.every(([key, value]) => o[key] === value));
  
console.log(matches);

注意:如果您只想获取第一个匹配的对象,请使用Array#find而不是Array#filter


推荐阅读