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

编程入门 行业动态 更新时间:2024-10-09 12:26:54
本文介绍了传播具有动态属性的嵌套javascript对象的语法以进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 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:无法读取未定义的属性"1" 我该如何使用传播语法来获得像这样的分组结果.

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"] } }

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

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

推荐答案

只需添加一些 sh * t和棍棒:

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

更多推荐

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

本文发布于:2023-11-05 10:07:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1560553.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   语法   属性   对象   动态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!