传播具有动态属性的嵌套javascript对象的语法以进行分组

时间:2019-02-07 21:59:11

标签: javascript ecmascript-6 spread-syntax

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

均返回错误TypeError: Cannot read property '1' of undefined 我如何使用传播语法来获得像这样的分组结果。

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

} 

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

1 个答案:

答案 0 :(得分:2)

只需添加一些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);