Reputation: 1467
I have an array. Pretty simple, like: [32652,24164]
both of which numbers are stored productID
s
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
Upvotes: 1
Views: 59
Reputation: 9412
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]
Upvotes: 1