資料迴圈處理重組2
阿新 • • 發佈:2018-12-28
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body><script> var arr = [{ "temperatures": [{ "legend": "A相溫度", "unit": null, "yaxis": "21.1", "xaxis": "11" }, { "legend": "B相溫度", "unit": null, "yaxis": "21.8", "xaxis": "11" }, { "legend": "C相溫度", "unit": null, "yaxis": "20.9", "xaxis": "11" }, { "legend": "N相溫度", "unit": null, "yaxis": "21.4","xaxis": "11" }], "voltages": [{ "legend": "A相電壓", "unit": null, "yaxis": "242.0", "xaxis": "11" }, { "legend": "B相電壓", "unit": null, "yaxis": "240.0", "xaxis": "11" }, { "legend": "C相電壓", "unit": null, "yaxis": "248.0", "xaxis": "11" }], "currents": [{ "legend": "A相電流", "unit": null, "yaxis": "9.9", "xaxis": "11" }, { "legend": "B相電流", "unit": null, "yaxis": "17.2", "xaxis": "11" }, { "legend": "C相電流", "unit": null, "yaxis": "1.5", "xaxis": "11" }], }, { "temperatures": [{ "legend": "A相溫度", "unit": null, "yaxis": "21.2", "xaxis": "11" }, { "legend": "B相溫度", "unit": null, "yaxis": "21.9", "xaxis": "11" }, { "legend": "C相溫度", "unit": null, "yaxis": "21.1", "xaxis": "11" }, { "legend": "N相溫度", "unit": null, "yaxis": "21.5", "xaxis": "11" }], "voltages": [{ "legend": "A相電壓", "unit": null, "yaxis": "242.0", "xaxis": "11" }, { "legend": "B相電壓", "unit": null, "yaxis": "240.0", "xaxis": "11" }, { "legend": "C相電壓", "unit": null, "yaxis": "248.0", "xaxis": "11" }], "currents": [{ "legend": "A相電流", "unit": null, "yaxis": "9.9", "xaxis": "11" }, { "legend": "B相電流", "unit": null, "yaxis": "17.2", "xaxis": "11" }, { "legend": "C相電流", "unit": null, "yaxis": "1.5", "xaxis": "11" }] }]; // console.log(arr); // var final=[]; //最終要生成的陣列 // // 把type和name加進去 // for(var i=0;i<arr[0].temperatures.length;i++){ // final[i]={}; // final[i].type='line' // final[i].name=arr[0].temperatures[i].legend // } // // console.log(final) // //先把data需要用到的資料存起來 // var dataArr=[] // for(var i=0;i<final.length;i++){ // dataArr[i]=[] // } // // console.log(dataArr) //得到4個空陣列 // arr.forEach(item=>{ // item.temperatures.forEach((sonItem,index)=>{ // dataArr[index].push(sonItem.yaxis) // }) // }) // // console.log(dataArr) //得到需要的陣列 // final.forEach((item,index)=>{ // item.data=dataArr[index] // }) // console.log(final) function makeArr(sourceArr,type,typeName){ var final=[]; var dataArr=[]; for(var i=0;i<sourceArr[0][type].length;i++){ final[i]={}; final[i].type=typeName final[i].name=sourceArr[0][type][i].legend } // console.log(final) var dataArr=[] for(var i=0;i<final.length;i++){ dataArr[i]=[] } // console.log(dataArr) sourceArr.forEach(item=>{ item[type].forEach((sonItem,index)=>{ dataArr[index].push(sonItem.yaxis) }) }) // console.log(dataArr) final.forEach((item,index)=>{ item.data=dataArr[index] }) return final } var test=makeArr(arr,'currents','line') console.log(test) </script> </body> </html>