我可以根据主题进行分组,但主题是一个数组。我怎么组由各个科目吗?
let a =
[
{
Name: 'Josh',
Subject: ['Biology', 'Chemistry'],
},
{
Name: 'James',
Subject: ['Chemistry', 'Physics'],
},
{
Name: 'Mary',
Subject: ['Physics', 'Mathematics'],
},
]
const result = a.reduce((groupedSubject, person) => {
const Subject = person.Subject
if(groupedSubject[Subject]== null) groupedSubject[Subject] = []
groupedSubject[Subject].push(person)
return groupedSubject
}, {})
console.log(result)
我可以根据主题进行分组,但主题是一个数组。我怎么组由各个科目吗?
您还需要迭代Sports
数组。
const
data = [{ Name: 'Ravindra', Sports: ['Chess', 'Cricket'] }, { Name: 'Ravi', Sports: ['Cricket', 'Football'] }, { Name: 'Rishabh', Sports: ['Table-Tennis', 'Football'] }],
result = data.reduce((groupedSports, person) => {
person.Sports.forEach(sport => {
groupedSports[sport] ??= [];
groupedSports[sport].push(person.Name);
})
return groupedSports;
}, {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
您可以遍历所有体育项目并检查它是否已经存在,如果不存在,则展开所有当前条目并将新的人员Name
添加到数组中。
let a = [{
Name: 'Ravindra',
Sports: ['Chess', 'Cricket'],
},
{
Name: 'Ravi',
Sports: ['Cricket', 'Football'],
},
{
Name: 'Rishabh',
Sports: ['Table-Tennis', 'Football'],
},
]
const result = a.reduce((groupedSports, person) => {
person.Sports.forEach((sport) => {
groupedSports[sport] = groupedSports?.[sport]
? [...groupedSports[sport], person.Name]
: [person.Name];
});
return groupedSports;
}, {});
console.log(result)