const data = [{year:2019,month:1,id:"xd1"},
{year:2019,month:1,id:"xd2"},
{year:2019,month:1,id:"xd4"},
{year:2019,month:2,id:"xd1"},
{year:2018,month:1,id:"rd3"},
{year:2018,month:2,id:"rd6"},
{year:2018,month:2,id:"rd7"}
]
const result = data.reduce((state,d)=>{
return {
...state,
[d.year]:{
...state[d.year],
[d.month]:[
...state[d.year][d.month]
,d.id]
}
}
},{})
console.log(result);
const result = data.reduce((state,d)=>{
return {
...state,
[d.year]:{
...state[d.year],
[d.month]:[].concat([state[d.year][d.month]],[d.id])
}
}
},{})
both return an Error TypeError: Cannot read property '1' of undefined
How can I use the spread syntax to get a grouped result like this.
{'2019':{
'1':["xd1","xd2","xd3"],
'2':["xd1"]},
'2018':{
'1':["rd3"],
'2':["rd6","rd7"]
}
}
Please consider using reduce and spread syntax and not chaining other methods because the its actually part of a bigger construct and other things wont help.
Thx.
EDIT: like stated in the comments. I would explicitly like solve it inline with spread operator that returns new objects or arrays. No extra libraries like lodash.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…