Home > OS >  Java Script/Vue.Js group by an object base on name
Java Script/Vue.Js group by an object base on name

Time:10-16

I would like to group by an object based on partial name and add them into variables

data =
{
   SCHOOL-ADMISSION_YEAR: "2021"
   SCHOOL-SCHOOL_NAME: "ABC SCHOOL"
   SCHOOL-SCHOOL_LOCATION: "NEWYORK"
   ENROLLMENT-ADMISSION_YEAR: "2021"
   ENROLLMENT-SUBMISSION_DATE: "2020-04-02"
   ENROLLMENT-ENROLLMENT_DATE: "2020-06-02"
}

The group should be

 School =
  {
   ADMISSION_YEAR: "2021",
   SCHOOL_NAME: "ABC SCHOOL",
   SCHOOL_LOCATION: "NEWYORK",
  }

 Enrollment =
  {
   ADMISSION_YEAR: "2021",
   SUBMISSION_DATE: "2020-04-02",
   ENROLLMENT_DATE: "2020-06-02",
  }

var school = data.filter(p => p.contains('SCHOOL'));
var enrollment = data.filter(p => p.contains('ENROLLMENT'));

CodePudding user response:

Plain objects don't have filter method and need to be iterated with a loop. In order to be filtered and mapped, an object can be converted to entry array and back, e.g with ES2019 fromEntries:

const school = Object.fromEntries(
  Object.entries(data)
  .filter(([key]) => key.includes('SCHOOL-'))
  .map(([key, val]) => [key.replace('SCHOOL-', ''), val])
);

For an array of objects it's:

const school = Object.entries(data)
  .filter(([key]) => key.includes('SCHOOL-'))
  .map(([key, val]) => ({ [key.replace('SCHOOL-', '')]: val }));

CodePudding user response:

I think this will work for you:

function getAllWithSubstring(substring) {
  let dataWithSubstring = [];

  for (let key of Object.keys(data)) {
    if (key.includes(substring)) {
      dataWithSubstring.push(data[key])
    }
  }
  return dataWithSubstring;
}

Then you can call it like this:

getAllWithSubstring("SCHOOL"); // => ['2021', 'ABC SCHOOL', 'NEWYORK']
getAllWithSubstring("ENROLLMENT"); // => ['2021', '2020-04-02', '2020-06-02']
  • Related