尝试在阵列上运行过滤器时未定义

时间:2016-05-17 10:09:16

标签: javascript filter

我有一个数组。非常简单,例如:[32652,24164]这两个数字都存储在productID s

我有一个对象存储与每个productID

相关联的数据
var products = {
  "products": [{
    "productID": "32652",
    "name": "Playstation 4",
    "price": "109.99"
  }, {
    "productID": "24164",
    "name": "Xbox",
    "price": "129.99"
  }]
};

我尝试使用name

尝试在对象中找到关联的priceproductID以及.filter

我有以下功能:

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');
  }
}

这是不起作用的特定代码行。这应返回结果,但它会回来undefined

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

因此该函数永远不会运行,也永远不会找到关联的nameprice

我已将JS Fiddle

组合在一起

1 个答案:

答案 0 :(得分:1)

你错过了一个parseInt。您正在尝试严格比较字符串和int

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

将其改为此

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