Hey folks I am getting an array of objects from a response. I need to flatten all of the students objects to simply studentName but not certain how. Any help would be greatly appreciated.
Example Array:
JavaScript
x
11
11
1
[
2
{
3
students: {id: '123456', name: 'Student Name'},
4
active: true
5
},
6
{
7
students: {id: '123456', name: 'Student Name'},
8
active: true
9
}
10
]
11
What I am trying to do:
JavaScript
1
11
11
1
[
2
{
3
studentName: 'Student Name',
4
active: true
5
},
6
{
7
studentName: 'Student Name',
8
active: true
9
}
10
]
11
Advertisement
Answer
You can create and return a new array of result using map
as:
JavaScript
1
17
17
1
const arr = [
2
{
3
students: { id: "123456", name: "Student Name" },
4
active: true,
5
},
6
{
7
students: { id: "123456", name: "Student Name" },
8
active: true,
9
},
10
];
11
12
const result = arr.map(({ students, rest }) => ({
13
rest,
14
studentName: students.name,
15
}));
16
17
console.log(result);