1

I have an array. Pretty simple, like: [32652,24164] both of which numbers are stored productIDs

I have an object storing data associated with each productID

var products = {
  "products": [{
    "productID": "32652",
    "name": "Playstation 4",
    "price": "109.99"
  }, {
    "productID": "24164",
    "name": "Xbox",
    "price": "129.99"
  }]
};

I'm trying to find the associated name and price in the object along with the productID by using .filter

I have the following function:

function findProductData(productID) {
  var foundProductArray = [];

  var foundProduct = products.products.filter(x => x.productID === productID)[0];

  console.log(foundProduct); // THIS IS COMING BACK UNDEFINED
  if (foundProduct) {
  // This function is never running as the filter is coming back UNDEFINED
    console.log('Something found');
    var foundName = foundProduct.name;
    var foundPrice = foundProduct.price;
    foundProductArray.push(foundName, foundPrice);
    return foundProductArray;
  } else {
    console.log('Nothing found');
  }
}

This is the particular line of code that is not working. This should return a result, but it's coming back undefined

var foundProduct = products.products.filter(x => x.productID === productID)[0];

So the function is never running and never finding the associated name and price.

I've put together a JS Fiddle

1
  • === means value and type. try == Commented May 17, 2016 at 10:24

1 Answer 1

1

You missed a parseInt. You are trying to strictly compare a string and an int

 .filter(x => x.productID === productID)[0]

Change that to this

.filter(x => parseInt(x.productID) === productID)[0]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.