考虑到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))
发布于 2020-12-03 23:22:58
因为@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,正如您所提到的,您可以使用它,如果没有它,您将不得不对代码进行更多更改才能工作。
https://stackoverflow.com/questions/65128398
复制相似问题