如何在reactjs中按值对对象数组进行分组

how to group array of objects by value in reactjs

考虑 array

const a1 = [
  { id: 1, nome: 'Ruan', status: { id: 1, posicao: 'goleiro' } },
  { id: 2, nome: 'Gleison', status: { id: 2, posicao: 'zagueiro' } },
  { id: 3, nome: 'Geraldo', status: { id: 2, posicao: 'zagueiro' } },
  { id: 4, nome: 'Heleno', status: { id: 3, posicao: 'atacante' } },
  { id: 5, nome: 'Djandel', status: { id: 3, posicao: 'atacante' } }
]

我尝试使用 reduce,但没有成功,我尝试了下面的代码

var groupBy = function(xs, key) {
  return xs.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
  groupBy(a1, 'status')
};

我也试过 lodash

_.groupBy(a1, 'status');

我希望 3 个不同的 arrays 会 return,一个 goleiros,另一个 zagueiros,另一个 atacantes

以及如何在react视图中单独显示信息?

你可以这样使用分组方式:

_.groupBy(a1, "status.posicao")

要指定您需要按 status.posicao 对它们进行分组,请查看此沙箱,它将 return 一个包含三个组的对象。

https://codesandbox.io/s/strange-sanne-icdy3?file=/src/index.js

编辑:

如果您想在不使用 lodash 的情况下构建自己的函数并假设您知道对象的形状,则可以构建类似这样的东西(我正在使用您的数组示例):

const a1 = [
  { id: 1, nome: "Ruan", status: { id: 1, posicao: "goleiro" } },
  { id: 2, nome: "Gleison", status: { id: 2, posicao: "zagueiro" } },
  { id: 3, nome: "Geraldo", status: { id: 2, posicao: "zagueiro" } },
  { id: 4, nome: "Heleno", status: { id: 3, posicao: "atacante" } },
  { id: 5, nome: "Djandel", status: { id: 3, posicao: "atacante" } },
];

function groupBy(items) {
  return items.reduce((acc, curr) => {
    if (curr.status?.posicao) {
      const { posicao } = curr.status;
      const currentItems = acc[posicao];
  
      return { 
        ...acc,
        [posicao]: currentItems ? [...currentItems, curr] : [curr]
      };
    }
    return acc;
  }, {});
}

console.log(groupBy(a1))

因为 @jean182 已经告诉您 lodash 示例中的问题是什么,但没有告诉您如何修复您的代码,我添加这个是为了回答问题的那一部分。

reduce 中的问题是你将 status 作为键,但 status 是一个对象,因此你将使用它的内存地址作为键而不是值这里永远不会有相同的键 (rv[x[key]] = rv[x[key]] || []) 并且每次你都会退回到空数组。为了使您的代码正常工作,您可以将其更改为如下内容:

var groupBy = function(xs, key) {
    return xs.reduce(function(rv, x) {
        const value = _.get(x, key)
        (rv[value] = rv[value] || []).push(x);
        return rv;
    }, {});
};
groupBy(a1, 'status.posicao')

请记住,我在这里使用的是 lodash get,正如您提到的,您可以使用它,如果没有它,您将不得不对代码进行更多更改才能正常工作。