skip to Main Content

I am new to JavaScript and I am stuck.
I have an array of objects below

const   items = [
{
  "product": "apple",
  "quantity": 3
},
{
  "product": "orange",
  "quantity": 1
},
{
  "product": "mango",
  "quantity": 0.6
},
{
  "product": "pineapple",
  "quantity": 52
},
{
  "product": "banana",
  "quantity": 23
},
{
  "product": "avocado",
  "quantity": 14
}

]

I am trying to display these on a table and would like to get the quantity for each row based on the product, so if for instance it is a row for banana, I get 23.

What I have attempted so far is

 function specs(gizmo){
   var found = items.filter(obj => obj.product === gizmo);
   return found[0]?.quantity
 }

  console.log(specs('banana')); 

This works if I hard-code the array, but when I pull it from Firestore, which is my Backend. I get the error:

Cannot read properties of undefined (reading '0')

I have tried adding a fallback but that still fails to work.

2

Answers


  1. For you use case you should use array.find. Note that you will still need to use optional chaining since the returned value could be undefined.

    Login or Signup to reply.
  2. As others already mentioned, use find() instead.

    You can also create a custom function that loops trough the array and searches for the item. I made an example below.

    function specs(itemToFind) {
      for(const item of items) {
        if(item.product === itemToFind) {
          return item;
        }
      }
      
      return null; // return something else if item was not found.
    }
    
    console.log(specs("banana"));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search