Pivot a JavaScript Array: Convert a Column to a Row(前端列转行)
2021-05-31 16:03
标签:name ice == jquery src aci art post query 看看我 Sometimes we need to convert a column to row in JavaScript array. It might be helpful to pass it as web service argument, generating chart dynamically or to display data in more meaningful way. In this post, we will create a method which converts a specified column to row in JavaScript array like below: In above method: The logic of method is simple. First it iterates the given array and create a result object of [rowIndex],[colIndex] = [dataIndex] format so that it can be fetched easily by using associative array like syntax. In the same iteration, we put unique values of colIndex in newCols array which will be used to create new columns. After this loop, we will get result object and newCols array. Now create a return array (ret), push newCols values for Header data and iterate result object, push values in ret object. Finally, ret variable will have the converted array. In this post, we have converted one column to row in JavaScript array and display data accordingly. Pivot a JavaScript Array: Convert a Column to a Row(前端列转行) 标签:name ice == jquery src aci art post query 原文地址:https://www.cnblogs.com/vvull/p/14744863.html
Consider the following array:
var arr = [
//["Product", "Year", "Sales"],
["Product 1", "2009", "1212"],
["Product 2", "2009", "522"],
["Product 1", "2010", "1337"],
["Product 2", "2011", "711"],
["Product 2", "2012", "2245"],
["Product 3", "2012", "1000"]
];
Now add following method to get converted array:
function getPivotArray(dataArray, rowIndex, colIndex, dataIndex) {
//Code from https://techbrij.com
var result = {}, ret = [];
var newCols = [];
for (var i = 0; i
dataArray: Array to be converted
rowIndex: Index of column in array which is to be kept as first column
colIndex: Index of column whose values to be converted as columns in the output array.
dataIndex: Index of column whose values to be used as data (displayed in tabular/grid format).
Here is example to use the above method:
var output = getPivotArray(arr, 0, 1, 2);
To show array in HTML table, add following javascript function:
function arrayToHTMLTable(myArray) {
var result = "
";
for (var i = 0; i ";
for (var j = 0; j " + myArray[i][j] + "";
}
result += "";
}
result += "
";
return result;
}
on HTML side, add following
Original Array
Converted Array
Here jQuery is used to display table
$(function () {
var output = getPivotArray(arr, 0, 1, 2);
$(‘#orgTable‘).html(arrayToHTMLTable(arr));
$(‘#pivotTable‘).html(arrayToHTMLTable(output));
});
Hope, It helps.
下一篇:从零开始的C++学习札记
文章标题:Pivot a JavaScript Array: Convert a Column to a Row(前端列转行)
文章链接:http://soscw.com/essay/89785.html