2 qq 28399261 qq_28399261 于 2017.08.28 09:23 提问

JavaScript数据转换问题

如何用JavaScript把 var string = "112312312312100,112312312312103,112312312312105-111,112312312312106,112312312312102";
转换成类似 [{"earMark":"112312312312100"},{"earMark":"112312312312103"},{"earMark":"112312312312105-111"},{"earMark":"112312312312106"},{"earMark":"112312312312102"}]

3个回答

FluxMode
FluxMode   2017.08.28 09:41
已采纳

var array = string.split(",");
var arrays = [];
array.forEach(function(el){ arrays.push({"earMark":el})});
var string = JSON.stringify(arrays);

showbo
showbo   Ds   Rxr 2017.08.28 09:39

    var string = "112312312312100,112312312312103,112312312312105-111,112312312312106,112312312312102";
    string = "[" + string.replace(/([^,]+)/g, '{"earMark":"$1"}') + "]";
    console.log(string)
    var o = eval('(' + string + ')');
    console.log(o)

haihhhhh
haihhhhh   2017.08.28 09:34

先把string用字符串隔开得到字符串数组。
循环拼上固定的jsion字符,就好了。

 var string="112312312312100,112312312312103,112312312312105-111,112312312312106,112312312312102";
var array=string.split(",");
var stringBuffer="[";
for(var i=0;i<array.length;i++){
if(i!=0)stringBuffer+=",";
    stringBuffer+="{"";
            stringBuffer+="\"earMark\"";
        stringBuffer+=":";
        stringBuffer+="\"";
        stringBuffer+=array[i];
        stringBuffer+="\"";
            stringBuffer+="}";

}
 stringBuffer+="]";
Csdn user default icon
上传中...
上传图片
插入图片