在键:值数组中转换简单字符串

时间:2015-07-02 17:19:37

标签: javascript arrays

我在JavaScript中使用了以下字符串:

test: hi,
otherTest: hiAgain

如何在key:value数组中进行转换?

3 个答案:

答案 0 :(得分:2)

var string = 'test: hi,otherTest: hiAgain';
var sets = string.split(","); //splits string by commas
var out = new Array(); //prepare the output array
for (var i=0; i<sets.length; i++) {
  var keyval = sets[i].split(":"); //split by colon for key/val
  out[keyval[0]] = keyval[1].trim(); //trim off white spaces and set array
}

答案 1 :(得分:1)

这是一个简单的例子:

myArray

答案 2 :(得分:1)

你在这里:

var data = ['test: hi', 'otherTest: hiAgain'];
var result = [];
$.each(data, function(index, value){
    var keyValue = value.split(':');
    var obj = {};
    obj[keyValue[0].trim()] = keyValue[1].trim();
    result.push(obj);
});
alert(JSON.stringify(result));

希望得到这个帮助。