我有以下字符串:
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 syntax和 computed property names .
关于javascript - 使用字符串中的键/值对创建对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48994206/