Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Split object propery values and create new array of object if they split

I have object like this. I getting this object on backend with query and then transform with qs string library.

{ 
color: 'red,white',
size: 'xl', 
manufacturer: 'adidas,nike' 
}

I would like have array of object, what i need for prisma map filtering

  const filterList = [
    {filter: "color", value: "red"},
    {filter: "color", value: "white"}, 
    {filter: "size", value: "xl"},
    {filter: "manufacturer", value: "adidas"},
    {filter: "manufacturer", value: "nike"},
  ];

How can i this handle ? Thanks for a reply

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To create the desired array of objects from the original object, you can use the Object.entries() method to get an array of key-value pairs, then use Array.map() to iterate over the key-value pairs and create the array of objects.

Here is an example:

const obj = { 
  color: 'red,white',
  size: 'xl', 
  manufacturer: 'adidas,nike' 
};

const filterList = Object.entries(obj).map(([filter, value]) => {
  return value.split(",").map(v => ({ filter, value: v }));
}).flat();

console.log(filterList);

This will output the following array:

[
  {filter: "color", value: "red"},
  {filter: "color", value: "white"}, 
  {filter: "size", value: "xl"},
  {filter: "manufacturer", value: "adidas"},
  {filter: "manufacturer", value: "nike"},
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading