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

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

通過匹配數組檢索值

通過匹配數組檢索值

DIEA 2021-06-01 17:46:46
選中復選框的值與數組交叉匹配以過濾結果。如何選擇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">
查看完整描述

3 回答

?
LEATH

TA貢獻1936條經驗 獲得超7個贊

具有正確選擇器的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>


查看完整回答
反對 回復 2021-06-03
?
幕布斯6054654

TA貢獻1876條經驗 獲得超7個贊

您可以使用document.querySelectorAll(".fruits:checked")class 獲取所有已檢查的元素.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 />


查看完整回答
反對 回復 2021-06-03
?
弒天下

TA貢獻1818條經驗 獲得超8個贊

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


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


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

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



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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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