1

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'));
2
  • Nothing that is shown is specific to Vue. It's JS. Commented Oct 15, 2021 at 15:43
  • Thank you.I will update the title. Commented Oct 15, 2021 at 15:46

2 Answers 2

1

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 }));
Sign up to request clarification or add additional context in comments.

5 Comments

I have one more question if you don't mind.Instead of creating single object ,can i create an array of objects.Each key value will be an object inside an array.
What exactly should the resulting array look like?
[ {ADMISSION_YEAR: "2021"}, {SCHOOL_NAME: "ABC SCHOOL"}, {SCHOOL_LOCATION: "NEWYORK"} ]
Updated. Generally an array of objects with one key is not very practical, ES6 Map may be more suitable as iterable collection of key value pairs. And in Vue an object is easily iterable in v-for as well.
Thank you very much.working as expected.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.