可以使用Array.map
方法結合對象取值方式進行篩選,例如:
假設有如下數組:
const arr = [
{ id: 1, name: 'apple', price: 2 },
{ id: 2, name: 'banana', price: 3 },
{ id: 3, name: 'durian', price: 5 },
{ id: 4, name: 'cherry', price: 1 },
{ id: 5, name: 'apple', price: 4 }
];
如果要取出所有對象中name
為apple
的物品的price
屬性值,可以這樣執行:
const prices = arr.filter(item => item.name === 'apple').map(item => item.price);
console.log(prices); // [2, 4]
先通過Array.filter
方法篩選出name
屬性值為apple
的對象,然后通過Array.map
方法將所有對象中的price
屬性值取出存入數組中。最終輸出結果為[2, 4]
。