我有一系列对象,我试图转换成一个新数组。我只是试图重新排列数据的结构,但遗憾的是没有得到理想的结果。
我的数据是作为一个对象数组而来的,我认为是这样的:
data = Team > Days > Games
收到的数据是一个阵列,其中包含他们可能在周一至周日(0-6)播放的运动队和比赛。
我需要转换这些数据,使其结构如下:
data = Days > Teams > Games
示例数据:
var data = [
{
id: 1,
team: 'LA Lakers'
days: [
{
id: 0,
name: 'Monday',
games: [
{
id: 1,
home: false
},
{
id: 2,
home: true
},
{
id: 3,
home: true
}
]
},
{ id: 1, name: 'Tuesday', games:[] },
{ id: 2, name: 'Wednesday', games:[] },
{ id: 3, name: 'Thursday', games:[] },
{ id: 4, name: 'Friday', games:[] },
{ id: 5, name: 'Saturday', games:[] },
{ id: 6, name: 'Sunday', games:[] }
]
},
{
id: 2,
team: 'NJ Nets'
days: [
{ id: 0, name: 'Monday', games:[] },
{ id: 1, name: 'Tuesday', games:[] },
{
id: 2,
name: 'Wednesday',
games: [
{
id: 1,
home: false
},
{
id: 2,
home: true
},
{
id: 3,
home: true
}
]
},
{ id: 3, name: 'Thursday', games:[] },
{ id: 4, name: 'Friday', games:[] },
{ id: 5, name: 'Saturday', games:[] },
{ id: 6, name: 'Sunday', games:[] }
]
},
];
我想要的结果:
var newData = [
{
id: 0,
name: 'Monday',
teams: [
{
id: 1,
name: 'LA Lakers'
games: [
{
id: 1,
home: false
},
{
id: 2,
home: true
},
{
id: 3,
home: true
}
]
}
]
},
{ id:1, name:'Tuesday', teams:[] },
{
id: 2,
name: 'Wednesday',
teams: [
{
id: 1,
name: 'NJ Nets'
games: [
{
id: 1,
home: false
},
{
id: 2,
home: true
},
{
id: 3,
home: true
}
]
}
]
},
.
.
.
.
];
我能够利用lodash,并且可能认为groupby功能可能有用,或者只是可能使用for循环将信息推送到新数组中?任何建议都表示赞赏。
答案 0 :(得分:0)
我的解决方案lodash 4.17.4
const res = _.chain(data)
.flatMap('days')
.uniqBy('id')
.map(_.partialRight(_.omit, 'games')) // get all days without games
.map((day) => { // iterate days
// get teams withs games at this day
const teamsWithGames = _.chain(data)
.filter(team => _.some(team.days, { id: day.id })) // filter teams by day
.map(_.partialRight(_.omit, 'days')) // delete days from teams
.map((team) => {
// assign games at this day to team
return _.chain(data)
.find({ id: team.id })
.get('days')
.filter({ id: day.id })
.flatMap('games')
.thru(games => _.assign({}, team, { games }))
.value();
})
.filter(team => _.size(team.games) > 0)
.value();
return _.assign({}, day, { teams: teamsWithGames }); // return day with teams
}, [])
.value();