首页 > 解决方案 > Match with multiple arrays

问题描述

I start with multiple arrays. Then based on the checkbox selection I would like to crosscheck the value with the item array and get the relevant values from the price and exp arrays.

<input type="checkbox" name="grocery" value="peach">
<input type="checkbox" name="grocery" value="apple">
<input type="checkbox" name="grocery" value="orange">

example if the 2nd check box is checked (value="apple") then I need to be able to get its values separately.

This is what I have so far. How do I match the selected checkbox values to the item array to be able to gather the values from the price, exp and lot arrays? I am looking for a way to do it in vanilla javascript.

let item = ["peach", "apple", "orange"];
let price = [21, 32, 18];
let exp = [21, 18, 25];
let lot = [6, 8, 4];
let crossCheck = [];

let items = document.getElementsByName('grocery');
for(var i = 0; i < items.length; i++) {
    if(items[i].type == 'checkbox' && items[i].checked) {
        crossCheck.push(items[i].value);
        console.log(s)
    }
}

标签: javascript

解决方案


The best way I think you using the array of object.

let array = [
    { "item": "peach", "price": 21, "exp": 21, "lot": 6 },
    { "item": "apple", "price": 32, "exp": 18, "lot": 8 },
    { "item": "orange", "price": 18, "exp": 25, "lot": 4 }
]

after define you can add to crossCheck

crossCheck.push(array[i])

Hope this solution can help you. Thanks for reading


推荐阅读