javascript构造json数组

从后端拿到的数据是一个数组,每个元素中包含的数据如下(host相同的记录都是相邻的)

currentTime:"1470729601"
host:"10.3.34.21"
taskList:null
taskNum:1

想构造类似如下结构的json数组

[{

    name: 'host:10.1.6.49',
    data: [
        [1470641461000, 5],
        [1470642581000, 4],
        [1470643701000, 2],
        [1470647341000, 3]
    ]
}, {
    name: 'host:10.3.34.18',
    data: [
        [1470641461000, 2],
        [1470642581000, 2],
        [1470643701000, 1],
        [1470647341000, 4]
    ]
}, {
    name: 'host:10.2.2.22',
    data: [
        [1470641461000, 3],
        [1470642581000, 2],
        [1470643701000, 6],
        [1470647341000, 4]
    ]
},{
    name: 'host:10.1.110.96',
    data: [
        [1470641461000, 1],
        [1470642581000, 8],
        [1470643701000, 1],
        [1470647341000, 1]
    ]
},{
    name: 'host:10.2.2.87',
    data: [
        [1470641461000, 7],
        [1470642581000, 3],
        [1470643701000, 6],
        [1470647341000, 5]
    ]

}]


错误的方式:

var backendData = data.result;
var resultList = new Array();
var curHost = "";
var oneHostDataList = new Array();
for (var i in backendData) {
    var host = backendData[i].host;
    if (host != curHost) {
        if(i != 0) {
            var item = new Object();
            item.name = curHost;
            item.data = oneHostDataList;

            resultList.push(item);
        }
        oneHostDataList = new Array();
        curHost = host;
    }
    else {
        var dot = new Array();
        dot.push(backendData[i].currentTime * 1000);
        dot.push(backendData[i].taskNum);
        oneHostDataList.push(dot);
    }
}
var item = new Object();
item.name = curHost;
item.data = oneHostDataList;
resultList.push(item);
$scope.data = JSON.stringify(resultList);


以上方式的问题在于转换后会使得name和host和带上引号,正确的方式如下:

var backendData = data.result;
var resultList = [];
var curHost = "";
var oneHostDataList = new Array();
for (var i in backendData) {
    var host = backendData[i].host;
    if (host != curHost) {
        if(i != 0) {
            var item = {
                name: curHost,
                data: oneHostDataList
            };

            resultList.push(item);
        }
        oneHostDataList = new Array();
        curHost = host;
    }
    else {
        var dot = new Array();
        dot.push(backendData[i].currentTime * 1000);
        dot.push(backendData[i].taskNum);
        oneHostDataList.push(dot);
    }
}
var item = new Object();
item.name = curHost;
item.data = oneHostDataList;
resultList.push(item);
$scope.data = resultList;


你可能感兴趣的:(javascript构造json数组)