通过匹配数组检索值

时间:2019-05-16 17:06:41

标签: javascript

选中的复选框的值与数组交叉匹配,以过滤结果。如何选择pricelot的值?

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 个答案:

答案 0 :(得分:1)

您可以使用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 />

答案 1 :(得分:1)

具有适当选择器的

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>

答案 2 :(得分:0)

使用过滤器获取检查值。

然后映射数组并仅获取每个对象元素的值。

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

答案 3 :(得分:0)

您应该更改自己的结构

var inputElements = document.getElementsByName("fruits"); 
const items = {
"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 prices = [...inputElements].filter(elem => elem.checked).map(elem => items[elem.value]);

console.log(prices);
<input type="checkbox" name="fruits" value="lychee" checked>
 <input type="checkbox" name="fruits" value="orange">