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:
[
{
students: {id: '123456', name: 'Student Name'},
active: true
},
{
students: {id: '123456', name: 'Student Name'},
active: true
}
]
What I am trying to do:
[
{
studentName: 'Student Name',
active: true
},
{
studentName: 'Student Name',
active: true
}
]
[
{ students: {id: '123456', name: 'Student Name'}, active: true },
{ students: {id: '123456', name: 'Student Name'}, active: true }
].map(e => ({studentName: e.students.name, active: e.active}))
You can loop through the array and set each item's students property to the name property of the students property:
const arr = [
{students: {id: '123456', name: 'Student Name'},active: true},
{students: {id: '123456', name: 'Student Name'},active: true}
]
arr.forEach(e => e.students = e.students.name)
console.log(arr)
map over the data and return a new object on each iteration.
const data=[{students:{id:"123456",name:"Student Name"},active:!0},{students:{id:"123456",name:"Student Name"},active:!0}];
const out = data.map(obj => {
// Destructure the name and active properties
// from the object
const { students: { name }, active } = obj;
// Return the new object
return { studentName: name, active };
});
console.log(out);