2 回答

TA貢獻1862條經驗 獲得超7個贊
您的變量中有不必要的字符fishMonth,它應該是:
var fishMonth = `n_${currentMonth}`;
并且您還想讀取對象的密鑰,因此必須有return i[fishMonth] == true;,請嘗試:
const fishData = [{
"fish_name": "Barreleye",
"price": "15,000",
"location": "Sea",
"shadow_size": "Small",
"n_March": true,
"n_3": true,
},
{
"fish_name": "Coelacanth",
"price": "15,000",
"location": "Sea (Rainy Days)",
"shadow_size": "Largest",
"n_3": true,
}
]
var today = new Date();
var currentMonth = today.getMonth();
var fishMonth = `n_${currentMonth}`;
var filteredFish = fishData.filter(function(i) {
return i[fishMonth] == true;
});
console.log(filteredFish);

TA貢獻1828條經驗 獲得超6個贊
您需要沒有空格的正確鍵值和帶括號+的正確屬性訪問器。
您可以進行更多更改,例如直接從實例中獲取月份并直接返回所需屬性的值。
const
fishData = [{ fish_name: "Barreleye", price: "15,000", location: "Sea", shadow_size: "Small", n_March: true, n_3: true }, { fish_name: "Coelacanth", price: "15,000", location: "Sea (Rainy Days)", shadow_size: "Largest", n_3: true }],
fishMonth = `n_${(new Date).getMonth()}`,
filteredFish = fishData.filter(fish => fish[fishMonth]);
console.log(filteredFish);
最后,您可以更改整個數據結構并將月份作為值添加到對象并使用類似月份屬性的東西。這允許使用與值的簡單比較,而不是使用復合鍵。
const
fishData = [{ fish_name: "Barreleye", price: "15,000", location: "Sea", shadow_size: "Small", n_March: true, month: 3 }, { fish_name: "Coelacanth", price: "15,000", location: "Sea (Rainy Days)", shadow_size: "Largest", month: 3 }],
fishMonth = (new Date).getMonth(),
filteredFish = fishData.filter(({ month }) => month === fishMonth);
console.log(filteredFish);
添加回答
舉報