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.
asked May 3, 2020 at 20:07
arunmmanoharan
2,7073 gold badges38 silver badges76 bronze badges
-
1Does this answer your question? How to convert URL parameters to a JavaScript object?Ahmed Hammad– Ahmed Hammad2020年05月03日 20:09:31 +00:00Commented May 3, 2020 at 20:09
-
@AhmedHammad Yeah, got it by tweaking the regex a little bit. Thanksarunmmanoharan– arunmmanoharan2020年05月03日 20:19:57 +00:00Commented May 3, 2020 at 20:19
1 Answer 1
Object.fromEntries(
'client=66&instance=367&model=125'.split('&').map(it => it.split('='))
)
just delete the first '?':
let src = '?client=66&instance=367&model=125';
if (src[0] === '?') src = src.substring(1);
const obj = Object.fromEntries(
'client=66&instance=367&model=125'.split('&').map(it => it.split('='))
);
console.log(obj);
prints {client: "66", instance: "367", model: "125"}
answered May 3, 2020 at 20:26
crystalbit
7042 gold badges9 silver badges20 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js