我有一个这样的对象数组:

[
  {
    importantKey: 'x',
    foo: 'bar',
    ...
  },
  {
    importantKey: 'y',
    foo: 'bar',
    ...
  },
  {
    importantKey: 'z',
    foo: 'bar',
    ...
  },
  {
    importantKey: 'x',
    foo: 'bar',
    ...
  },
  {
    importantKey: 'y',
    foo: 'bar',
    ...
  },
  {
    importantKey: 'z',
    foo: 'bar',
    ...
  },
  ...
]

另一个数组具有importantKey的值:
keysArray = [x, y, z]

我将如何获得一个数组,该数组的值是所有importantKeykeysArray顺序相同的所有对象的计数?因此最终结果将是:
[ numberOfObjectsWithKeyX, numberOfObjectsWithKeyY, numberOfObjectsWithKeyZ ]

对于此示例,结果将是:
[2, 2, 2]

而且keysArray是动态生成的,因此xyz不能进行硬编码。

最佳答案

您可以执行以下操作:

keysArray.map(key => values.filter(v => v.importantKey === key).length);

基本上,您在map()上调用keysArray,这将为其创建一个并行数组,其中map()会吐出任何值。

对于该值,您只需调用values.filter()并仅过滤出具有适当键的内容,然后只需检查长度即可获得计数。

const values = [
  {
    importantKey: 'x',
    foo: 'bar'
  },
  {
    importantKey: 'y',
    foo: 'bar'
  },
  {
    importantKey: 'y',
    foo: 'bar'
  },
  {
    importantKey: 'x',
    foo: 'bar'
  },
  {
    importantKey: 'y',
    foo: 'bar'
  },
  {
    importantKey: 'z',
    foo: 'bar'
  }
];

const keys = ['x', 'y', 'z'];

const result = keys.map(key => values.filter(v => v.importantKey === key).length);

console.log(result);

关于javascript - 如何在现有数组中获取特定对象计数的数组?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43686999/

10-12 12:40
查看更多