javascript - 如何过滤数组内的对象?
问题描述
我想用单个对象检查数组内的条件。
let arr = [
{
name: "john",
description: {
height: 5.5,
weight: 54,
},
},
{
name: "mary",
description: {
height: 5.8,
weight: 65,
},
},
{
name: "smith",
description: {
height: 6.1,
weight: 85,
},
},
];
let obj = {
height: 5.8,
weight: 65,
};
我想比较数组中的 obj,如果它匹配一个,我想获取名称。例如,obj 等于结婚。我想打印玛丽。这是我尝试过的。
let result = arr.filter((item) => item.description === obj )
console.log(result.name);
解决方案
您可以使用对象的条目构建过滤器并迭代所有条目并检查值。然后映射名称。
let array = [{ name: "john", description: { height: 5.5, weight: 54 } }, { name: "mary", description: { height: 5.8, weight: 65 } }, { name: "smith", description: { height: 6.1, weight: 85 } }],
object = { height: 5.8, weight: 65 },
filters = Object.entries(object),
result = array
.filter(({ description }) => filters.every(([key, value]) => description[key] === value))
.map(({ name }) => name);
console.log(result);
推荐阅读
- r - R闪亮的数据不可用“错误:找不到对象”
- xamarin.android - 当我单击 SearchView 时,单击事件不会触发 (Xamarin.Android)
- html - Ruby和Rails:将一个视图的登录表单内容显示到另一个视图文件模式弹出窗口中
- actions-on-google - Google Home mini 不询问 DEVICE_COARSE_LOCATION
- c++ - 如何从 easy_curl 返回一个字符串?(用于 dll 的函数)C++
- python - 在 Unix 平台上将 Html 转换为 PDF Python/Django
- java - RecycleView 的 LayoutManager 有什么用?
- tcp - 本地计算机中的 UWP 客户端服务器
- freeradius - Freeradisu 允许基于 NAS-IDENTIFIER 的请求
- marklogic - 如何通过mlcp检查摄取速度慢的根本原因?