Skip to content
Advertisement

Flatten objects in array

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
 }
]

Advertisement

Answer

You can create and return a new array of result using map as:

const arr = [
  {
    students: { id: "123456", name: "Student Name" },
    active: true,
  },
  {
    students: { id: "123456", name: "Student Name" },
    active: true,
  },
];

const result = arr.map(({ students, ...rest }) => ({
  ...rest,
  studentName: students.name,
}));

console.log(result);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement