0

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.

arunmmanoharan
  • 2,535
  • 2
  • 29
  • 60
  • 1
    Does this answer your question? [How to convert URL parameters to a JavaScript object?](https://stackoverflow.com/questions/8648892/how-to-convert-url-parameters-to-a-javascript-object) – Ahmed Hammad May 03 '20 at 20:09
  • @AhmedHammad Yeah, got it by tweaking the regex a little bit. Thanks – arunmmanoharan May 03 '20 at 20:19

1 Answers1

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"}

crystalbit
  • 664
  • 2
  • 9
  • 19