【问题标题】:Sorting an array of objects with a variable filter使用变量过滤器对对象数组进行排序
【发布时间】:2020-04-15 20:58:32
【问题描述】:

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

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

【问题讨论】:

    标签: javascript arrays filter javascript-objects


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您需要不带空格的正确键值和+ 以及带括号的正确property accessor

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-19
        • 1970-01-01
        • 2016-04-26
        • 1970-01-01
        • 2014-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多