0

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.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Sky Lurk
  • 417
  • 1
  • 3
  • 13
  • can u log found. it is probably empty array. btw why not use find instead of filter since u are looking for 1 element in the array – cmgchess Mar 20 '23 at 19:30
  • use `find` instead of `filter` if you just want the first item. – Mina Mar 20 '23 at 19:32
  • found shows undefined for a second before it pulls from firestore, but then gets the data afterwards. Please show me how to use -find- on the array of objects – Sky Lurk Mar 20 '23 at 19:32
  • See also https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call for getting the results of the async call to Firebase. – Heretic Monkey Mar 20 '23 at 19:43

2 Answers2

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.

Dr. Vortex
  • 505
  • 1
  • 3
  • 16
1

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"));
rayman.io
  • 59
  • 4