Hi I have a array of students. Each students may have mulitple address (array) and multiple hobbies (array)
Structure as below:
const studentsList = {
students: [
{
id: '54654',
name: 'Tony',
address: [
{
location: 'SNG',
building: 2,
},
{
location: 'LON',
building: 3,
},
],
hobbies: [
{
name: 'soccer',
id: 123,
},
{
name: 'music',
id: 53,
},
],
},
{
id: '505389',
name: 'Stephen Strange',
address: [
{
location: 'LUX',
building: 8,
},
{
location: 'HK',
building: 25,
},
],
hobbies: [
{
name: 'watch tv',
id: 143,
},
{
name: 'music',
id: 83,
},
],
},
{
id: '34534389',
name: 'Wanda Maximoff',
address: [
{
location: 'HKG',
building: 89,
},
{
location: 'GEN',
building: 79,
},
],
hobbies: [
{
name: 'reading',
id: 45,
},
{
name: 'chess',
id: 37,
},
],
},
],
}
I would like to transform the student List to below format
1. Each student has a key of hobbies and each hobbies become a single hobby instead of a array
2. Each student has No key of address anymore, but has a key of loccation and building instead.
Like below
const studentsList = {
students: [
{
id: '54654',
name: 'Tony',
location: 'SNG',
building: 2,
hobbies: {
name: 'soccer',
id: 123,
},
},
{
id: '54654',
name: 'Tony',
location: 'LON',
building: 3,
hobbies: {
name: 'soccer',
id: 123,
},
},
{
id: '54654',
name: 'Tony',
location: 'SNG',
building: 2,
hobbies: {
name: 'music',
id: 53,
},
},
{
id: '54654',
name: 'Tony',
location: 'LON',
building: 3,
hobbies: {
name: 'music',
id: 53,
},
},
{
id: '505389',
name: 'Stephen Strange',
location: 'LUX',
building: 8,
hobbies: {
name: 'watch tv',
id: 143,
},
},
{
id: '505389',
name: 'Stephen Strange',
location: 'HK',
building: 25,
hobbies: {
name: 'watch tv',
id: 143,
},
},
{
id: '505389',
name: 'Stephen Strange',
location: 'HK',
building: 25,
hobbies: {
name: 'music',
id: 83,
},
},
{
id: '505389',
name: 'Stephen Strange',
location: 'LUX',
building: 8,
hobbies: {
name: 'music',
id: 83,
},
},
{
id: '34534389',
name: 'Wanda Maximoff',
location: 'HKG',
building: 89,
hobbies:{
name: 'reading',
id: 45,
},
},
{
id: '34534389',
name: 'Wanda Maximoff',
location: 'GEN',
building: 79,
hobbies:{
name: 'reading',
id: 45,
},
},
{
id: '34534389',
name: 'Wanda Maximoff',
location: 'HKG',
building: 89,
hobbies:{
name: 'chess',
id: 37,
},
},
{
id: '34534389',
name: 'Wanda Maximoff',
location: 'GEN',
building: 79,
hobbies:{
name: 'chess',
id: 37,
},
}
],
}
3
Answers
Here is the working logic :
Some crazy functional approach using
Array::reduce()
andArray::forEach()
.Basically you iterate hobbies for each student and inside the loop you add each address of the student to a new student item with the current hobby and student: