有没有一种高效的方法根据键-值对从对象数组中获取对象的值?

huangapple go评论65阅读模式
英文:

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"));

huangapple
  • 本文由 发表于 2023年3月21日 03:27:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75794515.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定