Home > Back-end >  How to split object into groups by matching key value similarity in TypeScript?
How to split object into groups by matching key value similarity in TypeScript?

Time:09-01

I am building an Angular application. I have to split my object into different objects by it's URI value, to later use in Expanding checkboxes solution (Being able to select All from the group, or specific ones). I am currently dealing with the splitting of the objects into groups.

StackBlitz data example

What is the most efficient way to put them in arrays accordingly to the uri part going after '/v2/'?

CodePudding user response:

This are two posible solutions that you could follow. The first one iterates over the array only once so I think could be the best way to go:

this.items.forEach((elem) => {
  if (elem.uri.startsWith('/v2/information/')) {
    this.groupInformation.push(elem);
  } else if (elem.uri.startsWith('/v2/payments/')) {
    this.groupPayments.push(elem);
  } else if (elem.uri.startsWith('/v2/menu/')) {
    this.groupMenu.push(elem);
  } else {
    // Do something else
  }
});

Here is another alternative:

this.groupInformation = this.items.filter((elem) =>
  elem.uri.startsWith('/v2/information/')
);
this.groupPayments = this.items.filter((elem) =>
  elem.uri.startsWith('/v2/payments/')
);
this.groupMenu = this.items.filter((elem) =>
  elem.uri.startsWith('/v2/menu/')
);

You could check it here

  • Related