[英]format array of object using reduce?
我有这个:
[
[
{
users: {
'ID': {
stage: 21,
city: 'london',
data: 2345
},
'ID2': {
stage: 21,
city: 'london',
data: 5325
}
}
},
{
users: {
'ID': {
stage: 21,
city: 'ny',
data: 5761
},
'ID2': {
stage: 21,
city: 'ny',
data: 5235
}
}
},
{
users: {
'ID': {
stage: 21,
city: 'stockholm',
data: 7433
},
'ID2': {
stage: 21,
city: 'stockholm',
data: 52365
}
}
}
],
[
{
users: {
'ID': {
stage: 22,
city: 'london',
data: 743
},
'ID2': {
stage: 22,
city: 'london',
data: 5325
},
}
},
{
users: {
'ID': {
stage: 22,
city: 'ny',
data: 152
},
'ID2': {
stage: 22,
city: 'ny',
data: 61632
},
}
},
{
users: {
'ID': {
stage: 13,
city: 'stockholm',
data: 2161
},
'ID2': {
stage: 22,
city: 'stockholm',
data: 62176
},
}
}
]
]
我想要这样的东西:
[
{
id: 'ID',
stages: {
21: {
cities: {
london: {
data: 2345
},
ny: {
data: 5761
},
stockholm: {
7433
}
}
},
22: {
cities: {
london: {
data: 5325
},
ny: {
data: 5235
},
stockholm: {
52365
}
}
}
}
},
{
id: 'ID2',
// same idea for this user
}
]
data
只是一个例子,有更多的元素,而不仅仅是一个
到目前为止,我尝试过使用reduce
map
和/或flat
array.flat().map(ar => Object.values(ar.players)).flat()
但是我不确定将其展平是否是最好的主意,并且我不知道该怎么做之后,我尝试使用reduce,但是我的尝试都没有成功。
您需要嵌套的方法并为相同的组构建新对象。
var data = [[{ users: { ID: { stage: 21, city: 'london', data: 2345 }, ID2: { stage: 21, city: 'london', data: 5325 } } }, { users: { ID: { stage: 21, city: 'ny', data: 5761 }, ID2: { stage: 21, city: 'ny', data: 5235 } } }, { users: { ID: { stage: 21, city: 'stockholm', data: 7433 }, ID2: { stage: 21, city: 'stockholm', data: 52365 } } }], [{ users: { ID: { stage: 22, city: 'london', data: 743 }, ID2: { stage: 22, city: 'london', data: 5325 } } }, { users: { ID: { stage: 22, city: 'ny', data: 152 }, ID2: { stage: 22, city: 'ny', data: 61632 } } }, { users: { ID: { stage: 13, city: 'stockholm', data: 2161 }, ID2: { stage: 22, city: 'stockholm', data: 62176 } } }]], result = Object.values(data .flat() .reduce((r, { users }) => { Object.entries(users).forEach(([id, { stage, city, data }]) => { r[id] = r[id] || { id, stages: {} }; r[id].stages[stage] = r[id].stages[stage] || { cities: {} }; r[id].stages[stage].cities[city] = { data }; }); return r; }, {}) ); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.