5 回答
TA贡献1877条经验 获得超6个赞
您可以使用对象的条目构建一个过滤器,并循环访问所有条目并检查值。然后映射名称。
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);
TA贡献1825条经验 获得超6个赞
您必须将所需的键相互比较,而不是比较对象,因为对象相等性基于它们的内存地址是否相同。
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
};
console.log(
arr.filter(item => item.description.height === obj.height && item.description.weight === obj.weight)
);
TA贡献1850条经验 获得超11个赞
一种方法是使用 .Object.keys
var 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, }}];
var obj = { height: 5.8, weight: 65 };
var result = arr.filter(({description})=>Object.keys(description).every(k=>description[k]==obj[k])).map(({name})=>name);
console.log(result);
TA贡献1809条经验 获得超8个赞
您可以缩小要过滤的属性范围,如下所示
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
};
const filtered = arr.filter(({ description }) => description.height === obj.height && description.weight === obj.weight);
console.log(filtered)
TA贡献1862条经验 获得超6个赞
筛选器筛选条件失败的根本原因是由于尝试的对象之间的比较。
对象的比较可以通过使用帮助程序函数来完成。
以下是工作原理:
// array-filter-demo.js
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 }
// Helper function to compare objects
function matching(a, b) {
return ( a.height === b.height && a.weight === b.weight)
}
// Call the helper function inside filter
const result = arr.filter(item => (matching(item.description, obj)))
console.log(result)
输出:
$ node array-filter-demo.js
[ { name: 'mary', description: { height: 5.8, weight: 65 } } ]
添加回答
举报