考虑到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返回,一个是goleiros,另一个是zagueiros,还有一个是atacantes
如何在react视图中单独显示信息?
发布于 2020-12-03 23:05:55
可以这样使用group by:
_.groupBy(a1, "status.posicao")要指定您需要按status.posicao对它们进行分组,请查看此沙箱,它将返回一个包含三个组的对象。
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))
https://stackoverflow.com/questions/65128398
复制相似问题