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

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

通過匹配數組來檢索值

通過匹配數組來檢索值

慕標琳琳 2019-04-18 18:19:18
選中復選框的值與數組交叉匹配到fileter結果。我該如何選擇price和lot值?var inputElements = document.getElementsByName("fruits"); const item = [{"lychee":{ price:10, lot:8}}, {"orange" :{ price:12, lot:6}},{"apple" :{ price:8, lot:3}},{"mango"  :{ price:12, lot:5}},{"banana" :{ price:4, lot:1}}];    var checked = [...inputElements].map(item => {   if(item.checked){     return item.value   }}).filter(item => item);console.log(checked); <input type="checkbox" name="fruits" value="lychee" checked> <input type="checkbox" name="fruits" value="orange">
查看完整描述

4 回答

?
開心每一天1111

TA貢獻1836條經驗 獲得超13個贊

querySelectorAll使用適當的選擇器將為您提供選中的值:

const item = { 

  "lychee": {"price": 10,"lot": 8},

  "orange": {"price": 12,"lot": 6},

  "apple":  {"price": 8, "lot": 3},

  "mango":  {"price": 12,"lot": 5},

  "banana": {"price": 4, "lot": 1}

};

let res = [...document.querySelectorAll("[name=fruits]:checked")]

             .map(chk => `${chk.value},lot:${item[chk.value].lot}, price:${item[chk.value].price}`);

document.getElementById("res").innerHTML = res.join("<br/>");

<input type="checkbox" name="fruits" value="lychee" checked> lychee <br />

<input type="checkbox" name="fruits" value="orange"> orange <br />

<input type="checkbox" name="fruits" value="banana" checked> banana <br />

<br/>

<span id="res"></span>


查看完整回答
反對 回復 2019-05-17
?
慕的地6264312

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


您可以使用document.querySelectorAll(".fruits:checked")獲取所有帶有類的已檢查元素.fruits。Set用它的值創建一個對象。


使用filter的過濾器item陣列。


var checked = new Set(Array.from(document.querySelectorAll(".fruits:checked")).map(o => o.value));

const item = [{"lychee":{"price":10,"lot":8}},{"orange":{"price":12,"lot":6}},{"apple":{"price":8,"lot":3}},{"mango":{"price":12,"lot":5}},{"banana":{"price":4,"lot":1}}];


let result = item.filter(o => checked.has(Object.keys(o)[0]));


console.log(result);

<input class="fruits" type="checkbox" name="fruits" value="lychee" checked> lychee <br />

<input class="fruits" type="checkbox" name="fruits" value="orange"> orange <br />

<input class="fruits" type="checkbox" name="fruits" value="banana" checked> banana <br />


查看完整回答
反對 回復 2019-05-17
?
飲歌長嘯

TA貢獻1951條經驗 獲得超3個贊

使用過濾器獲取選中的值。


然后映射數組并僅獲取每個對象元素的值。


var checked = [...inputElements].filter(inputElement => inputElement.checked);

var valuesOfChecked = checked.map(item => [Object.values(item)[0].price,Object.values(item)[0].lot])


查看完整回答
反對 回復 2019-05-17
  • 4 回答
  • 0 關注
  • 493 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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