简体   繁体   中英

How to pivot a data-ng-repeat data in Jquery?

I am having a data like below

Supplier A
ProductID 1001
Price 2.3
Supplier A
Product ID 2001
Price 4.3
Supplier A
Product ID 3001
Price 4.6
Supplier B
ProductID 1001
Price 5.3
Supplier B
Product ID 2001
Price 5.0
Supplier B
Product ID 3001
Price 5.6

I use the below code to display the data as it is

<tr data-ng-repeat="Emp in EmpAddressList">
    <td>{{Emp.rackPrice.SupplierName}}</td>
    <td>{{Emp.rackPrice.ProductID}}</td>
    <td>{{Emp.rackPrice.Price}}</td>                
</tr>

but i want to display the data in a pivoted format

Supplier     1001    2001    3001
A            2.3     4.3     4.6 
B            5.0     5.2     5.6

Can some one help me to modify this code

thanks

Create an array for the headings using the product ID's and an object for the pivot data

Repeating rows for suppliers from pivotData and then repeating the headings gives you 2 properties to get the price for that column and row.

If you need a more robust sortable table...map the pivotData object to arrays instead

 var app = angular.module('app', []); app.controller('MainCtrl', function($scope) { var pivotData = $scope.pivotData = {}, headings = $scope.headings = []; data.forEach(o => { if (!headings.includes(o.ProductID)) { headings.push(o.ProductID) } pivotData[o.Supplier] = pivotData[o.Supplier] || {}; pivotData[o.Supplier][o.ProductID] = o.Price }); headings.sort((a, b) => a - b); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script> <div ng-app="app" ng-controller="MainCtrl"> <table> <tr> <th>Supplier</th> <th ng-repeat="h in headings">{{h}}</th> </tr> <tr ng-repeat="(supp, obj) in pivotData"> <th>{{supp}}</th> <td ng-repeat="h in headings">{{obj[h]}}</td> </tr> </table> <h4>PivotData</h4> <pre>{{pivotData|json}}</pre> </div> <script> var data = [{ "Supplier": "A", "ProductID": "1001", "Price": "2.3" }, { "Supplier": "A", "ProductID": "2001", "Price": "4.3" }, { "Supplier": "A", "ProductID": "3001", "Price": "4.6" }, { "Supplier": "B", "ProductID": "1001", "Price": "5.3" }, { "Supplier": "B", "ProductID": "2001", "Price": "5.0" }, { "Supplier": "B", "ProductID": "3001", "Price": "5.6" }] </script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM