简体   繁体   中英

Convert string to object - Javascript

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(/[az]+|[^az]+/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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM