亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用變量過濾器對對象數組進行排序

使用變量過濾器對對象數組進行排序

三國紛爭 2022-07-01 16:52:47
我試圖按當月過濾我的對象數組。以動物穿越魚為例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。什么會阻止這個工作?
查看完整描述

2 回答

?
牧羊人nacy

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


查看完整回答
反對 回復 2022-07-01
?
30秒到達戰場

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


查看完整回答
反對 回復 2022-07-01
  • 2 回答
  • 0 關注
  • 115 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號