繁体   English   中英

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

[英]Sorting an array of objects with a variable filter

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

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 什么会阻止这个工作?

您的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);

您需要没有空格和+的正确键值以及带括号的正确属性访问器

您可以进行更多更改,例如直接从实例中获取月份并直接返回所需属性的值。

 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM