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

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

基于復選框過濾對象數組

基于復選框過濾對象數組

喵喵時光機 2021-12-23 14:44:05
您好,我想根據選中的復選框過濾我的數據。我有 3 個復選框。<input type="checkbox" name="shoes" value="shoes" class="storesCheckBox" /><input type="checkbox" name="clothes" value="clothes" class="storesCheckBox" /><input type="checkbox" name="sports" value="sports" class="storesCheckBox" />我的商店數據是// my storesvar stores = [    {        id: 1,        store: 'Store 1',        storeType: "shoes"    },    {        id: 2,        store: 'Store 2',        storeType: "clothes"    },    {        id: 3,        store: 'Store 3',        storeType: "sports"    },    {        id: 4,        store: 'Store 3',        storeSells: "shoes"    }]所以,如果我選中shoes復選框,我想根據 storeType 過濾數據shoes。所以我寫了var getStores = stores.filter(function (store) {    return store.storeType === 'shoes';});但是現在,如果我檢查clothes并且shoes已經檢查。我想過濾shoes + clothes數據。如果我取消選中,shoes我只想過濾衣服數據。它可以是任意數量的復選框,具體取決于商店類型。你能幫我解決這個問題嗎?
查看完整描述

3 回答

?
UYOU

TA貢獻1878條經驗 獲得超4個贊

你可以試試這個:


var storeTypesSelected; //array of the types checked

var getStores = stores.filter(function (store) {

    return storeTypesSelected.indexOf(store.storeType) > -1;

});


查看完整回答
反對 回復 2021-12-23
?
慕妹3242003

TA貢獻1824條經驗 獲得超6個贊

從選中的復選框中,構建所選值的數組(或集)。然后,在遍歷數組時,檢查當前storeType是否包含在集合中:


var stores = [{

    id: 1,

    store: 'Store 1',

    storeType: "shoes"

  },

  {

    id: 2,

    store: 'Store 2',

    storeType: "clothes"

  },

  {

    id: 3,

    store: 'Store 3',

    storeType: "sports"

  },

  {

    id: 4,

    store: 'Store 3',

    storeType: "shoes"

  }

];


document.addEventListener('change', () => {

  const checkedValues = [...document.querySelectorAll('.storesCheckBox')]

    .filter(input => input.checked)

    .map(input => input.value);

  const filteredStores = stores.filter(({ storeType }) => checkedValues.includes(storeType));

  console.log(filteredStores);

});

Shoes: <input type="checkbox" name="shoes" value="shoes" class="storesCheckBox" />

Clothes: <input type="checkbox" name="clothes" value="clothes" class="storesCheckBox" />

Sports: <input type="checkbox" name="sports" value="sports" class="storesCheckBox" />


查看完整回答
反對 回復 2021-12-23
?
拉風的咖菲貓

TA貢獻1995條經驗 獲得超2個贊

您只需要在數組中保存用于過濾的復選框值。


var elems = document.getElementsByClassName("storesCheckBox");

var list = [];

for(var i=0; elems[i]; ++i){

      if(elems[i].checked){

           list.push(elems[i].value);

      }

}

var getStores = stores.filter(function (store) {

    return list.indexOf(store.storeType) >= 0;

});

return 語句將使用 indexOf 函數進行過濾。


查看完整回答
反對 回復 2021-12-23
  • 3 回答
  • 0 關注
  • 168 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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