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.

2

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.