使用变量过滤器对对象数组进行排序

我试图按当月过滤我的对象数组。以动物穿越鱼为例


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}`;

console.log(fishMonth);

var filteredFish = fishData.filter(function(i) {

    return i.fishMonth == true;

});

现在返回,如果我放"n_3"而不是"fishMonth"代码运行良好。我已经检查过了"fishMonth",它确实返回了n_3。什么会阻止这个工作?


三国纷争
浏览 100回答 2
2回答

牧羊人nacy

您的变量中有不必要的字符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);

30秒到达战场

您需要没有空格的正确键值和带括号+的正确属性访问器。您可以进行更多更改,例如直接从实例中获取月份并直接返回所需属性的值。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);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript