I have the following url with params:
abc?carbs=pasta,rice,noodles&sauce=tomato&wine=red
As you can see, carbs is an array divided by a comma.
So, by using the following code:
sourceURL
.slice(1)
.split('&')
.map(p => p.split('='))
.reduce((obj, pair) => {
const [key, value] = pair.map(decodeURIComponent);
return { ...obj, [key]: value };
}, {});
I get this NOT CORRECT result:
{
"carbs": "pasta,rice,noodles",
"sauce": "tomato",
"wine": "red"
}
What I would like is the following: (EXPECTED)
{
"carbs": ["pasta","rice","noodles"],
"sauce": "tomato",
"wine": "red"
}
Any way someone can help? Thanks in advance, Joe
UPDATE:
Some of the responses are great, thanks, everyone. Unfortunately, they all return carbs as an Object if it contains only 1 value.
For example, if my URL is abc?carbs=noodles&sauce=tomato&wine=red I should get:
{
"carbs": ["noodles"], <----- still an array even with 1
"sauce": "tomato",
"wine": "red"
}
but unfortunately, all the provided solutions return the following:
{
"carbs": "noodles",
"sauce": "tomato",
"wine": "red"
}
Sorry if it wasn't clear before. Thanks Joe