【问题标题】:How to count a number of specific elements in an object?如何计算对象中特定元素的数量?
【发布时间】:2020-04-27 03:47:54
【问题描述】:

我有一组物品fruitItems,看起来像这样:

[
    {
        "name": "banana",
        "origID": "7064012136"
    },
    {
        "name": "apple",
        "origID": "8390108418"
    },
    {
        "name": "pineapple",
        "origID": "8317598430"
    },
    {
        "name": "banana",
        "origID": "8395091043"
    },
    {
        "name": "orange",
        "origID": "8391923474"
    }
]

如何获取此列表中banana 的编号? 我试过这样做:

fruitItems.name.filter(x => x === "banana").length;

但它会抛出ReferenceError: fruitItems is not defined,即使它已定义。

【问题讨论】:

  • 你也可以发布定义
  • fruitItems.filter(x => x.name === 'banana').length;
  • 是的,我把.name放错地方了,非常感谢

标签: javascript object numbers filtering counting


【解决方案1】:

更干净的解决方案:)

const fruits = [{
  "name": "banana",
  "origID": "7064012136"
}, {
  "name": "apple",
  "origID": "8390108418"
}, {
  "name": "pineapple",
  "origID": "8317598430"
}, {
  "name": "banana",
  "origID": "8395091043"
}, {
  "name": "orange",
  "origID": "8391923474"
}];


const count = fruits.reduce((acc, {
  name
}) => name === 'banana' ? acc + 1 : acc, 0); //2

console.log(count)

【讨论】:

    【解决方案2】:

    语法修正:

    const data = [{
        "name": "banana",
        "origID": "7064012136"
      },
      {
        "name": "apple",
        "origID": "8390108418"
      },
      {
        "name": "pineapple",
        "origID": "8317598430"
      },
      {
        "name": "banana",
        "origID": "8395091043"
      },
      {
        "name": "orange",
        "origID": "8391923474"
      }
    ]
    
    const res = data.filter(({
      name
    }) => name === "banana").length;
    
    console.log(res)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-04
      • 1970-01-01
      • 2018-11-21
      相关资源
      最近更新 更多