具有用于分组的动态属性的嵌套 javascript 对象的传播语法

Spread syntax for nested javascript object with dynamic properties for grouping

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])
        }
    }
},{})

两个return一个错误TypeError: Cannot read property '1' of undefined 我如何使用传播语法来获得这样的分组结果。

{'2019':{
   '1':["xd1","xd2","xd3"],
   '2':["xd1"]},
 '2018':{
   '1':["rd3"],
   '2':["rd6","rd7"]
 }

} 

请考虑使用 reduce 和 spread 语法,不要链接其他方法,因为它实际上是更大结构的一部分,其他方法无济于事。 谢谢。 编辑:如评论中所述。我想明确地想用 returns 新对象或数组的扩展运算符内联解决它。没有像 lodash 这样的额外库。

只需添加一些 sh*t and sticks:

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);