Home > Software design >  Mapping through array of objects after filtering and displaying dynamic common property as a header
Mapping through array of objects after filtering and displaying dynamic common property as a header

Time:12-10

I have an array of objects:

  const students = [
    { name: 'Tom', class: "Blue" },
    { name: 'Pom', class: "Blue" },
    { name: 'Max', class: "Red" },
    { name: 'Alex', class: "Red" },
    { name: 'John', class: "Yellow" }
  ];

And I would like to group the return values by the class property, so I can achieve something similar to this in HTML:

Class Blue: Tom, Pom
Class Red: Max, Alex
Class Yellow: John

note: the class property should be displayed once as HTML mark-up which is the reason I don't think enter image description here

CodePudding user response:

You could create a new object with the name of the classes as keys and an array with the names of the students as values.

const students = [
    { name: 'Tom', class: "Blue" },
    { name: 'Pom', class: "Blue" },
    { name: 'Max', class: "Red" },
    { name: 'Alex', class: "Red" },
    { name: 'John', class: "Yellow" }
];

let klasses = {};

for (let i = 0; i < students.length; i  ) {
  let student = students[i];
  let klass = student.class;

  if (!klasses[klass]) {
    klasses[klass] = [student.name];
  } else {
    klasses[klass].push(student.name);
  }
}

console.log(klasses);

CodePudding user response:

let classes = {};

for(let student of students) {
  classes[student.class] = [...classes[student.class] || [], student.name];
}

console.log(classes);
  • Related