节点JS ProductProvider.getItem未在JSON中找到项目

我对JavaScript相当陌生,所以如果我缺少一些简单的东西,请原谅我。我一直在疯狂地搜寻Google,找不到答案。

我正在尝试在JSON中查找特定记录。原谅我,我来自关系数据库背景。

我有以下JSON:

Add to Cart tempProducts:[[{"inCart":false,"price":0,"_id":"5ec94e7649116e38802efb7d","title":"MyTitle","filePath":"/Uploads/Capture.JPG","createdAt":"2020-05-23T16:25:26.066Z","updatedAt":"2020-05-23T16:25:26.066Z","__v":0},{"inCart":false,"price":0,"_id":"5ec94ea049116e38802efb7e","title":"MyTitle2","filePath":"/Uploads/Capture.JPG","createdAt":"2020-05-23T16:26:08.892Z","updatedAt":"2020-05-23T16:26:08.892Z","__v":0},{"inCart":false,"price":0,"_id":"5ec94ed649116e38802efb80","title":"MyTitle3","filePath":"/Uploads/capture3.JPG","createdAt":"2020-05-23T16:27:02.309Z","updatedAt":"2020-05-23T16:27:02.309Z","__v":0}]]

我正在寻找这个ID:

id: 5ec94ea049116e38802efb7e

您可以看到此ID在上面的JSON中存在。

这是我的代码(这是部分方法):

addToCart = id => {
    console.log("id: " + id)
    let tempProducts = [this.state.products];
    console.log("Add to Cart tempProducts:" + JSON.stringify(tempProducts));

    console.log("Add to Cart Products:" + JSON.stringify(this.state.products));
    const index = tempProducts.indexOf(this.getItem(id));
    //const index = tempProducts.data.indexOf(item => item.id === id);
    console.log("index: " + index)
    const product = tempProducts[index];

控制台日志ID显示正确的ID。

Her is a screenshot of the output: enter image description here

注意索引是-1。

有谁知道为什么getItem方法找不到匹配的ID?

谢谢。

评论
  • rtotam
    rtotam 回复
    • you're converting your tempProducts to a string then you try to find the index of an item which've became a part of a string, you don't need to stringfy your tempProducts

      let tempProducts = [this.state.products];
      
      const index = tempProducts.indexOf(item=>item.id===id); //will return you the index or -1 if it didn't find it