skip to Main Content

I have a collection in a JSON file, when I access it by http://localhost:5000/product/ I see it, but when I try to get a specific product from it, like http://localhost:5000/product/1 I see nothing but [], what could be a possible solution to this?

I expect the output of http://localhost:5000/product/1 to be
{
"Id": 1,
"name": "Milk",
"Quantity": 100,
"Unit_coast": 2000
}

enter image description here

enter image description here

2

Answers


  1. create get productById new API end point

    the logic :

    function getProductById(productId) {
      const filteredProducts = products.filter(item => item.Id === productId);
      return filteredProducts;
    }
    
    Login or Signup to reply.
  2. jsut note that the filter method will always return an array – ieither use an index or use find()

    as per Berlin Johns. M answer – but with an index on the return

    function getProductById(productId) {
      const filteredProducts = products.filter(item => item.Id === productId);
       return filteredProducts[0];
     }
    

    or use find to return the indidivudal item

    function getProductById(productId) {
       return products.find(item => item.Id === productId);
    }
    

    and if you want to use more current arrow function

    getProductById(productId) => products.find(item => item.Id === productId)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search