Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

ecmascript 6 - 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.

{'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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just add some 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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...