简体   繁体   English

将字符串转换为 object - Javascript

[英]Convert string to object - Javascript

I have a string and would like to convert it to an object based upon certain conditions.我有一个字符串,想根据某些条件将其转换为 object。

My string here is '?client=66&instance=367&model=125' .我的字符串是'?client=66&instance=367&model=125' I would like to convert it to an object like我想将其转换为 object 之类的

{
  "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"}打印{client: "66", instance: "367", model: "125"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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