您好,登錄后才能下訂單哦!
小編給大家分享一下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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。