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 } } ]
添加回答
舉報