我正在努力应对一个严格的要求,我不知道如何应对
我收到了一个数组如下:
[{
"student": "21_A_1",
"sport": "badminton"
}, {
"student": "21_C_1",
"sport": "badminton"
}, {
"student": "21_A_2",
"sport": "badminton"
}, {
"student": "21_B_1",
"sport": "football"
}, {
"student": "21_A_2",
"sport": "football"
}]
要求:将其转换为格式为:
的数组[{
"student": "21_A_1",
"sport": ["badminton"]
}, {
"student": "21_C_1",
"sport": ["badminton"]
}, {
"student": "21_A_2",
"sport": ["badminton","football"]
}, {
"student": "21_B_1",
"sport": ["football"]
}]
我发现lodash库有一个功能" group by"返回非常封闭的结果,但不是期望:
_.groupBy(array, 'student');
结果:
{
"21_A_1": [{
"student": "21_A_1",
"sport": "badminton"
}],
"21_C_1": [{
"student": "21_C_1",
"sport": "badminton"
}],
"21_A_2": [{
"student": "21_A_2",
"sport": "badminton"
}, {
"student": "21_A_2",
"sport": "football"
}],
"21_B_1": [{
"student": "21_B_1",
"sport": "football"
}]
}
非常感谢任何建议。
答案 0 :(得分:2)
我们可以使用数组的'.reduce'函数和聚合结果如下
var test = [{
"student": "21_A_1",
"sport": "badminton"
}, {
"student": "21_C_1",
"sport": "badminton"
}, {
"student": "21_A_2",
"sport": "badminton"
}, {
"student": "21_B_1",
"sport": "football"
}, {
"student": "21_A_2",
"sport": "football"
}]
const result = test.reduce((res,x)=>{
res[x.student] = res[x.student] || { student:x.student,sport:[]}
res[x.student].sport.push(x.sport)
return res;
},{})
console.log(result)
答案 1 :(得分:2)
您需要使用sport
属性映射分组的项目,并使用分组信息构建新对象。
var array = [{ student: "21_A_1", sport: "badminton" }, { student: "21_C_1", sport: "badminton" }, { student: "21_A_2", sport: "badminton" }, { student: "21_B_1", sport: "football" }, { student: "21_A_2", sport: "football" }],
grouped = _(array)
.groupBy('student')
.map((group, student) => ({ student, sport: _.map(group, 'sport') }))
.value();
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
答案 2 :(得分:0)
使用Array.prototype.reduce()结合Object.values():
const data = [{"student": "21_A_1","sport": "badminton"}, {"student": "21_C_1","sport": "badminton"}, {"student": "21_A_2","sport": "badminton"}, {"student": "21_B_1","sport": "football"}, {"student": "21_A_2","sport": "football"}];
const result = Object.values(
data.reduce((a, c) => ((a[c.student] = a[c.student] || {student: c.student, sport: []}).sport.push(c.sport), a), {})
);
console.log(result);