比方说,我们有一个关于以团队为对象排列的团队的以下数据,我们的任务是将这些数据转换为对象,以键作为角色,值作为玩家名称数组。
我们的样本数组-
const team = [{ role: 'Batsman', player: 'V Kohli' }, { role: 'Wicket Keeper', player: 'KL Rahul' }, { role: 'Batsman', player: 'R Sharma' }, { role: 'Wicket Keeper', player: 'R Pant' }, { role: 'Bowler', player: 'B Kumar' }, { role: 'Bowler', player: 'M Shami' }, ]
让我们定义一个objectify()
将数组作为参数并返回相应对象的函数。
为此的代码将是-
const objectify = (team) => { const teamObject = {}; team.forEach(member => { if(teamObject[member.role]){ teamObject[member.role].push(member.player); }else{ teamObject[member.role] = [member.player]; } }); return teamObject; } console.log(objectify(team));
在这里,我们逐一循环遍历每个数组项,如果在teamObject中存在,则将玩家推入其值,否则我们将为单个玩家分配一个数组
这是完整的代码-
const team = [{ role: 'Batsman', player: 'V Kohli' }, { role: 'Wicket Keeper', player: 'KL Rahul' }, { role: 'Batsman', player: 'R Sharma' }, { role: 'Wicket Keeper', player: 'R Pant' }, { role: 'Bowler', player: 'B Kumar' }, { role: 'Bowler', player: 'M Shami' }, ] const objectify = (team) => { const teamObject = {}; team.forEach(member => { if(teamObject[member.role]){ teamObject[member.role].push(member.player); }else{ teamObject[member.role] = [member.player]; } }); return teamObject; } console.log(objectify(team));
输出结果
控制台中此代码的输出为-
{ Batsman: [ 'V Kohli', 'R Sharma' ], WicketKeeper: [ 'KL Rahul', 'R Pant' ], Bowler: [ 'B Kumar', 'M Shami' ] }