String to Object literal

时间:2011-02-12 03:13:42

标签: javascript

是否可以转换字符串var:

 data="data1,data2,data3,data4"

到对象文字

data={
"data1":"data2",
"data3":"data4"
}

谢谢!

2 个答案:

答案 0 :(得分:6)

var arr = data.split(',');
var parsedData = {};
for (var i = 0; i < arr.length; i += 2) {
    parsedData[arr[i]] = arr[i + 1];
}

答案 1 :(得分:6)

这很简单:

function object_from_string(str) {
   var parts = str.split(','),
       obj   = {};
   for(var i = 0, j = parts.length; i < j; i+=2;) {
       obj[parts[i]] = parts[i+1];
   }
   return obj;
}

var data = "data1,data2,data3,data4";
var obj = object_from_string(data);
for(var k in obj) {
   if(obj.hasOwnProperty(k)) {
      console.log(k + ' = ' + obj[k]);
   }
}

输出:

data1 = data2
data3 = data4