【问题标题】:How to group by using reduce in Javascript如何在 Javascript 中使用 reduce 进行分组
【发布时间】:2023-01-12 18:42:23
【问题描述】:

我有一组对象,我想按米分组:

[
    {
        _id: { year:2022, meter:12 },
        x:1,
        y:0
    },
    ...
]

问题是我无法使用reduce 函数来这样做。我也尝试了其他方法,比如使用group

const result = inventory.group(({ _id.meter }) => _id.meter);

问题是没有一个方法接受密钥内的密钥(即_id 会工作但_id.meter 不会)

const products = [
  { name: 'apples', category: 'fruits' },
  { name: 'oranges', category: 'fruits' },
  { name: 'potatoes', category: 'vegetables' }
];

const groupByCategory = products.reduce((group, product) => {
  const { category } = product;
  group[category] = group[category] ?? [];
  group[category].push(product);
  return group;
}, {});

我在上面找到的另一个例子,如果我写 category.meter 或类似的东西,它再次不起作用。

有人可以帮助我如何修改代码,以便我能够按“键中键”对其进行分组吗?

【问题讨论】:

  • 当你说“按米分组”——你到底是什么意思?元素是否应该按 meter 的整数值分组,即一组用于 meter 值为 12 的元素,另一组用于 meter 值为 13,依此类推?
  • 在任何情况下,({ _id.meter }) => _id.meter 都不是有效的 JavaScript——如果您想将 meter 绑定到传递给函数的 _id 属性引用的对象的相应属性,则语法为 ({ _id: { meter } }) => meter

标签: javascript


【解决方案1】:

您只需要将嵌套属性值作为键。

data.reduce((r, o) => {
    const key = o.id.meter; // take group here
    (r[key] ??= []).push(o);
    return r;
}, {});

【讨论】:

    猜你喜欢
    • 2018-12-16
    • 2019-02-27
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    相关资源
    最近更新 更多