我得到了一些看起来像这样的数据。
var myData = [{Name : "Alex",Roll : 1,Class : 1,Marks :[{Maths: 100,Science : 200}],Weight: 50},
{Name : "Brat",Roll : 2,Class : 2,Marks :[{English: 100,History : 200 }],Weight: 40},
{Name : "Brat",Roll : 2,Class : 2,Marks :[{English: 100,History : 200 }],Weight: 30},
{Name : "Alex",Roll : 1,Class :1, Marks :[{Maths: 100,Science : 200, }],Weight: 60},
{Name : "Cean",Roll : 3,Class :1, Marks :[{Physic: 100,Economics : 200, }],Weight: 40}]
我尝试过的是这段代码。
function groupBy(xs, f) {
return xs.reduce((r, v, i, a, k = f(v)) => ((r[k] || (r[k] = [])).push(v), r), {});
}
这是将数据分组,但是我想存储到数组中。应该有两个键在外面,然后剩下的东西应该在集合下的数组内。
newData = [{Name : "Alex",
Roll: 1,
collection :[{Name : "Alex",Roll : 1,Class : 1,Marks :[{Maths: 100,Science : 200}],Weight: 50},
{Name : "Alex",Roll : 1,Class :1, Marks :[{Maths: 100,Science : 200, }],Weight: 60}]
},
{Name : "Brat",
Roll: 2,
collection :[{Name : "Brat",Roll : 2,Class : 2,Marks :[{English: 100,History : 200 }],Weight: 40},
{"Brat",Roll : 2,Class : 2,Marks :[{English: 100,History : 200 }],Weight: 30}]
},
{Name : "Cean",
Roll: 3,
collection :[{Name : "Cean",Roll : 3,Class :1, Marks :[{Physic: 100,Economics : 200, }],Weight: 40}],
}
]
任何人都可以帮助我修改我的代码,并帮助我达成解决方案。
答案 0 :(得分:2)
您可以使用Roll
作为键,如果存在,则将current element
添加到该特定Roll
的collection属性中,否则使用默认结构进行初始化
const myData = [{Name : "Alex",Roll : 1,Class : 1,Marks :[{Maths: 100,Science : 200}],Weight: 50},{Name : "Brat",Roll : 2,Class : 2,Marks :[{English: 100,History : 200 }],Weight: 40},{Name : "Brat",Roll : 2,Class : 2,Marks :[{English: 100,History : 200 }],Weight: 30},{Name : "Alex",Roll : 1,Class :1, Marks :[{Maths: 100,Science : 200, }],Weight: 60},{Name : "Cean",Roll : 3,Class :1, Marks :[{Physic: 100,Economics : 200, }],Weight: 40}]
let grouped = myData.reduce( (op,inp) => {
let { Roll } = inp
if( op[Roll] ) {
op[Roll].collection.push(inp)
} else{
op[Roll] = {Name: inp.Name, Roll, collection:[{...inp}]}
}
return op
},{})
console.log(Object.values(grouped))