mcadamsjustin mcadamsjustin - 9 months ago 36
Javascript Question

Jquery: Compare input values to array objects and see if they match exactly

I have 4 inputs, 2 text boxes and 2 radio buttons that I need to get the values of and compare to the objects in array and see if they are an exact match. The four inputs are:

<input type="text" id="brand">
<input type="text" id="prodNum">


radio 1

<input type="radio" name="radioYN" id="radioY" value="Yes">
<input type="radio" name="radioYN" id="radioN" value ="No">


radio 2

<input type="radio" name="radioStock" id="inStock" value="Ship">
<input type="radio" name="radioStock" id="outStock" value="Order">


I then take those values and put them in variables

var brand=$('input#brand').val();
var prodNum=$('input#prodNum').val();
var radioYN= $("input[name='radioYN']");
var radioStock= $("input[name='radioStock']");


All of that works fine, but I don't know how to compare that to the array and see if they match perfectly.Array:

var products = [
{
"brand": "brand1",
"prodNum": "01-005",
"YN": "Yes",
"Stock": "Order"
},
{
"brand": "brand2",
"prodNum": "02-005",
"YN": "Yes",
"Stock": "Ship"
},
{
"brand": "brand1",
"prodNum": "01-008",
"YN": "No",
"Stock": "Order"
}
]


I'll do and if statement to see if they match

if (inputs == array obeject){
//do something}
else {
//do something else}

Answer Source

Loop over items in products array and compare all the fields against the input values. Something like:

for (var i=0; i<products.length; i++) {
    var product = products[i];
    if (product.brand === brand && product.prodNum === prodNum && product.YN === radioYN && product.Stock === radioStock) {
        // do something
    }
    else {
        // do something else
    }
}