javascript - 使用字符串中的键/值对创建对象?

标签 javascript arrays regex string object

我有以下字符串:

person:juan&age:24&knowledge:html

问题是有时字符串是:

knowledge:html&person:juan&age:24

并且它可以改变键和值的位置。

在这种情况下,我会这样写:

const keys = ["person", "age", "knowledge"];
const keyAndValues = "person:juan&age:24&knowledge:html";

const result = [];

keys.forEach(key => {
  const indexKeyValues = keyAndValues.indexOf(key);
  if (indexKeyValues !== -1) {
    const lastCharIndex = keyAndValues.substring(indexKeyValues).indexOf("&");
    return keyAndValues.substring(indexKeyValues + key.length, lastCharIndex === -1 ? keyAndValues.substring(indexKeyValues).length - 1 || lastCharIndex);
  }
});

但我不喜欢它,如果我能做类似的事情就好了:

const resultsExpected = /regexGroupedRegardlessOfPosition/g.match("person:juan&age:24&knowledge:html");

console.log(resultsExpected); // { person: "juan", age: 24, knowledge: "html" }

最佳答案

这是获取对象的单个表达式:

const keyAndValues = "person:juan&age:24&knowledge:html";

const obj = Object.assign(...keyAndValues.split('&').map(s => s.split(':'))
                                         .map(([k, v]) => ({ [k]: v }))
);

console.log(obj);

这使用 ES6 destructuring assignment , spread syntaxcomputed property names .

关于javascript - 使用字符串中的键/值对创建对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48994206/

相关文章:

JavaScript Xpath : return result as string

javascript - Angular Universal 不会接管客户端的渲染

java - 将问号 (?) 替换为 (\\?)

javascript - float 的正则表达式

javascript - React - 如何解决 : "JSX expression must have parent and expression expected" error in vs code

javascript - 为什么作为参数传递的方法在这里不起作用

Java读取Json对象中的Json数组

javascript - Nodejs 从数组表达流

arrays - 在 python pandas 中组合字符串

python - 禁用 "\"字符 Python 2.7 的自动加倍 - re2 错误