javascript - 使用 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 完成此任务的干净方法。
解决方案
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
推荐阅读
- asp.net - 使用 DPL 通过以太网打印到 Pacesetter PS125,我可能需要哪些自定义配置 - 无法通信
- r - Dplyr 基于一列值合并行并对其他列求和
- php - 我们可以在 WordPress 中制作一个动态的图像,在 Style.css 中设置为背景吗?
- asp.net-web-api - 基本身份验证错误凭据的预期行为
- json - Powershell - 搜索 json 树
- unity3d - Vuforia & Unity:成功构建 UWP 但没有实时摄像头馈送(黑屏)
- python - 根据另一个数据框更改数据框列中的值
- datatables - 更新数据表中角度8的数据后清除数据
- javascript - 设置身份验证中间件以减少 Express.js 中的重复代码
- spring-boot - com.bedatadriven.jackson.datatype.jts.JtsModule 不适用于 springboot 2.2.4