英文:
Is there an efficient way to get the values of an object from an array of objects based on a key value pair
问题
function specs(gizmo){
var found = items.find(obj => obj.product === gizmo);
return found?.quantity;
}
console.log(specs('banana'));
英文:
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.
答案1
得分: 1
对于您的用例,您应该使用 array.find
。请注意,由于返回的值可能为未定义,您仍然需要使用可选链接。
英文:
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.
答案2
得分: 1
使用 find()
而非其他已提及的方法。
您还可以创建一个自定义函数,遍历数组并搜索项目。下面是一个示例:
function specs(itemToFind) {
for (const item of items) {
if (item.product === itemToFind) {
return item;
}
}
return null; // 如果未找到项目,可以返回其他内容。
}
console.log(specs("banana"));
英文:
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"));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论