传播具有动态属性的嵌套javascript对象的语法以进行分组 [英] Spread syntax for nested javascript object with dynamic properties for grouping
本文介绍了传播具有动态属性的嵌套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对象的语法以进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文