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);
添加回答
举报