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
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.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.