将字符串拆分为键值对

时间:2017-09-12 13:00:27

标签: javascript arrays

如果匹配key: value,我想用逗号分割以下字符串。用逗号分割,直到遇到value

中的逗号

const string = "country: Kenya, city: Nairobi, population: 3.375M, democracy-desciption: Work in progress/ Not fully met, obstacles exist"

我想结束这个结果:

[[country: Kenya],
[city: Nairobi],
[population: 3.375M],
[democracy-description: Work in progress/ Not fully met, obstacles exist]]

提前谢谢。

3 个答案:

答案 0 :(得分:3)

您可以通过查看是否跟随逗号和冒号来分割字符串。



var string = "country: Kenya, city: Nairobi, population: 3.375M, democracy-desciption: Work in progress/ Not fully met, obstacles exist, foo: bar, bar, bar";

console.log(string.split(/, (?=[^,]+:)/).map(s => s.split(': ')));

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 1 :(得分:1)

轻松:

const table =
 string.split(",") //["key:value","key:value"]
  .map(pair => pair.split(":")); //[["key","value"],["key","value"]]

用这个构建一个对象:

const result = {};
table.forEach(([key,value]) => result[key] = value);

//usable as:

console.log( result.country );

或使用js Map:

const result = new Map(table);

//usable as:

console.log( result.get("country") );

Try it out

答案 2 :(得分:1)

尝试这个...

function getParameters() {
    var paramStr = location.search.substring(1).split("&");
    var parameters = {}
    paramStr.map(item=>{
        let keyValue = item.split('=')
        return parameters[keyValue[0]] = keyValue[1];
    })
    return parameters;
}