mcadamsjustin mcadamsjustin -4 years ago 112
Javascript Question

set javascript variable to object in array from another variable

I have an array and two inputs. I'd like to take the value of the first input and place that in variable. I have that part down. I'd then like to use that variable to find the corresponding array entry and return another object from that array.

The input is

var prodNum=$('input#prodNum').val();


The array is:

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'd like to return the
"YN"
value to
var YNvalue
, given a certain
prodNum


For example if
prodNum
=
01-008
,
YNvalue
would be
"No"

Answer Source

You will have to loop over the objects in the product array until you find the one that matches:

function getProductYN(productList, productNumber) {
  for (var prodIdx = 0, prodCnt = productList.length; prodIdx < prodCnt; prodIdx++) {
    if (productList[prodIdx].prodNum === productNumber)
      return productList[prodIdx].YN;
  }
}

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"
  }
];

var prodNum = "01-008"; // $('input#prodNum').val();
var productYN = getProductYN(products, prodNum);

console.log(productYN);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download