简体   繁体   English

传播具有动态属性的嵌套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])
        }
    }
},{})

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. 都返回错误TypeError: Cannot read property '1' of undefined如何使用扩展语法获取这样的分组结果。

{'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. 请考虑使用reduce和spread语法,而不要链接其他方法,因为它实际上是较大结构的一部分,其他方面无济于事。 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. 没有像lodash这样的额外库。

Just add some sh*t and sticks : 只需添加一些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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM