如何在渲染morris图表之前过滤对象数组

时间:2015-08-17 14:44:37

标签: javascript jquery ajax asp.net-mvc-5 morris.js

我有一个通过adomd.net查询mdx的对象数组,在用ajax渲染我的图表之前我希望能够根据国家进行过滤,任何人都可以协助ajax请求中的方法来过滤例如只有包含“马耳他”的对象

非常感谢!

mdx result = [{"Country":"Canada","TY":50179.6,"SDLY":49933,"FCST YTD":null},{"Country":"Malta","TY":31757,"SDLY":33579,"FCST YTD":null},{"Country":"South Africa","TY":7380,"SDLY":8021,"FCST YTD":null},{"Country":"United Kingdom","TY":53249,"SDLY":69567,"FCST YTD":null},{"Country":"United States of America","TY":71771,"SDLY":89599,"FCST YTD":null}]

function createChart(data) {
        var mychart = new Morris.Bar({
            element: 'morris-bar-chart',
            data: data,
            xkey: 'Country',
            ykeys: ['TY','SDLY','FCST YTD'],
            labels: ['TY', 'SDLY', 'FCST YTD']
        });
    }

$.ajax({
        type: "GET",
        url: '@Url.Action("Test1", "Dashboard")',
        dataType: 'json',
        success: function (data) {
            var data = JSON.parse(data);
            createChart(data);
        },
        error: function () {
            alert("Error loading data! Please try again.");
        }
    });

1 个答案:

答案 0 :(得分:0)

您可以使用$.filter

    function filterByCountry(array, country){
       return array.filter(function(val){
          return val["Country"] == country;   
       });   
    }

    $.ajax({
           type: "GET",
           url: '@Url.Action("Test1", "Dashboard")',
           dataType: 'json',
           success: function (data) {
                    var data = JSON.parse(data);

                    var result = filterByCountry(data, "Malta");

                    createChart(result);
           },
           error: function () {
                    alert("Error loading data! Please try again.");
           }
    });

小提琴:http://jsfiddle.net/67pm0rnm/1/

过滤文档:http://api.jquery.com/filter/