Home > Back-end >  How to generate an array like this from the url query params
How to generate an array like this from the url query params

Time:12-13

From this:

const query = "cat_id=18,20,24&color_id=4";

or:

const urlObj = { cat_id: "18,20,24", color_id: "4" }

I need to create this:

const filteredItems = [
    {
      value:"18",
      queryKey:"cat_id"
    },
    {
      value:"20",
      queryKey:"cat_id"
    },
    {
      value:"24",
      queryKey:"cat_id"
    },
    {
      value:"4",
      queryKey:"color_id"
    }
]

CodePudding user response:

You cloud try const urlParams = new URLSearchParams(query);. More about this in the Docs

CodePudding user response:

Here's one implementation:

const urlObj = { cat_id: "18,20,24", color_id: "4" }

const filteredItems = Object.entries(urlObj).flatMap(([queryKey, value]) => {
  return value.split(",").map(v => ({ value: v, queryKey }))
})

console.log(filteredItems);

  • Related