I have a string and would like to convert it to an object based upon certain conditions.
My string here is '?client=66&instance=367&model=125'
. I would like to convert it to an object like
{
"client": 66,
"instance": 367,
"model": 125
}
I have managed to achieve it but wanting to find a better solution. Below is my implementation:
const path = '?client=66&instance=367&model=125';
const replacedPath = path.replace(/\?|&/g, '');
const clearedPath = replacedPath.match(/[a-z]+|[^a-z]+/gi).map(str => str.replace(/=/g, ''))
var output = {}
clearedPath.forEach((x, i, arr) => {
if (i % 2 === 0) output[x] = Number(arr[i + 1]);
});
console.log(output)
Please advice. Any help is highly appreciated.