小编给大家分享一下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数组的方法”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。