转换JavaScript对象数组

时间:2015-05-27 16:41:40

标签: javascript jquery underscore.js kendo-chart

我有以下两个JavaScript数组:

var grades = [ { name: "A", color: "#00FF00" }, 
               { name: "B", color: "#88CC00" },
               { name: "C", color: "#AAAA00" }, 
               { name: "D", color: "#CC8800" }, 
               { name: "F", color: "#FF0000" }];

var studentGrades = [ { Student: "James", Class: "Math", Grade: "A" },
                      { Student: "Lily", Class: "Math", Grade: "B" },
                      { Student: "Bob", Class: "Math", Grade: "C" },
                      { Student: "Tom", Class: "Math", Grade: "C" },
                      { Student: "James", Class: "Science", Grade: "A" },
                      { Student: "Lily", Class: "Science", Grade: "B" },
                      { Student: "Bob", Class: "Science", Grade: "B" },
                      { Student: "Tom", Class: "Science", Grade: "B" },
                      { Student: "James", Class: "Chemistry", Grade: "F" },
                      { Student: "Lily", Class: "Chemistry", Grade: "A" },
                      { Student: "Bob", Class: "Chemistry", Grade: "B" },
                      { Student: "Tom", Class: "Chemistry", Grade: "A" } ];

我正在尝试从中生成以下两个数组:

grades = [ { name: "A", color: "#00FF00", data: [1, 1, 2] },
                    { name: "B", color: "#88CC00", data: [1, 3, 1] },
                    { name: "C", color: "#AAAA00", data: [2, 0, 0] },
                    { name: "D", color: "#CC8800", data: [0, 0, 0] },
                    { name: "F", color: "#FF0000", data: [0, 0, 1] } ];

var classes = [ "Math", "Science", "Chemistry" ];

如果没有循环遍历studentGrades并维护计数和唯一的类列表,是否有一种简单的方法可以做到这一点?

修改:我在发布问题后创建了以下代码。我仍然更喜欢一种更容易阅读的方法。

<!DOCTYPE html>
<html>
  <head>
    <base href="http://demos.telerik.com/kendo-ui/bar-charts/local-data-binding">
    <style>html { font-size: 12px; font-family: Arial, Helvetica, sans-serif; }</style>
    <title></title>
    <link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.429/styles/kendo.common-bootstrap.min.css" />
    <link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.429/styles/kendo.bootstrap.min.css" />
    <link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.429/styles/kendo.dataviz.min.css" />
    <link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.429/styles/kendo.dataviz.bootstrap.min.css" />

    <script src="http://cdn.kendostatic.com/2015.1.429/js/jquery.min.js"></script>
    <script src="http://cdn.kendostatic.com/2015.1.429/js/kendo.all.min.js"></script>
  </head>
  <body>
    <div id="example">
      <div class="demo-section k-content">
        <div id="chart"></div>
      </div>
      <script>

        // Start of code that is specific to the stackoverflow question

        var grades = [ { name: "A", color: "#00FF00" }, 
                       { name: "B", color: "#88CC00" },
                       { name: "C", color: "#AAAA00" }, 
                       { name: "D", color: "#CC8800" }, 
                       { name: "F", color: "#FF0000" }];

        var studentGrades = [ { Student: "James", Class: "Math", Grade: "A" },
                              { Student: "Lily", Class: "Math", Grade: "B" },
                              { Student: "Bob", Class: "Math", Grade: "C" },
                              { Student: "Tom", Class: "Math", Grade: "C" },
                              { Student: "James", Class: "Science", Grade: "A" },
                              { Student: "Lily", Class: "Science", Grade: "B" },
                              { Student: "Bob", Class: "Science", Grade: "B" },
                              { Student: "Tom", Class: "Science", Grade: "B" },
                              { Student: "James", Class: "Chemistry", Grade: "F" },
                              { Student: "Lily", Class: "Chemistry", Grade: "A" },
                              { Student: "Bob", Class: "Chemistry", Grade: "B" },
                              { Student: "Tom", Class: "Chemistry", Grade: "A" } ];

        var classes = [];

        // Returns an array that maintains the grade counts for each class based on the grades array.
        var getGradeCounts = function (studentData, gradeCounts) {
            if (gradeCounts == null) {
                gradeCounts = [];
            }
            for (var i = 0; i < grades.length; i++) {
                if (gradeCounts[i] == undefined) {
                    gradeCounts[i] = 0;
                }
                if (grades[i].name === studentData.Grade) {
                    gradeCounts[i]++;
                }
            }
            return gradeCounts;
        }

        // Iterates over each student grade and maintains an object of the grade counts by class, and an unique array of classes used for the chart category.
        var classGradeCounts = {};
        for (var student in studentGrades) {
            var studentClass = studentGrades[student].Class;
            if (classGradeCounts[studentClass] == undefined) {
                classes.push(studentClass);
            }
            classGradeCounts[studentClass] = getGradeCounts(studentGrades[student], classGradeCounts[studentClass]);
        }

        // Now that we have the grade counts for each class, build up the chart series
        for (var i = 0; i < grades.length; i++) {
            grades[i].data = [];
            for (var classGradeCount in classGradeCounts) {
                grades[i].data.push(classGradeCounts[classGradeCount][i]);
            }
        }

        // End of stackoverflow code, the rest of this is code is used to generate a Kendo chart.

        var chartSettings = {
            seriesDefaults: { type: "column", stack: true },
            series: grades,
            categoryAxis: { categories: classes },
        };

        function createChart() {
          $("#chart").kendoChart(chartSettings);
        }

        $(document).ready(createChart);
        $(document).bind("kendo:skinChange", createChart);
      </script>
    </div>


  </body>
</html>

1 个答案:

答案 0 :(得分:3)

你无法避免循环。您可以使用Array.prototype.forEachArray.prototype.map等函数为其提供无循环的外观。

我认为最简单的方法是创建可让您快速访问所需数据的地图,这样您就不必经常扫描数组,也不需要underscore或{{1}等帮助程序}。这些地图的好处是您可以轻松地使用它们以更加轻松的方式生成不同格式的数据。

您可以研究产生所需输出的以下内容,并自行决定是否比使用常规循环更容易。

jQuery