代码之家  ›  专栏  ›  技术社区  ›  silverfighter

具有动态分组属性的嵌套javascript对象的扩展语法

  •  -1
  • silverfighter  · 技术社区  · 6 年前
    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语法,而不要链接其他方法,因为它实际上是更大构造的一部分,而其他的东西也无济于事。 谢谢。 编辑:如评论中所述。我想用返回新对象或数组的扩展运算符直接求解它。没有像罗达什这样的额外图书馆。

    1 回复  |  直到 6 年前
        1
  •  2
  •   Kosh    6 年前

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