Move values from JSON to javascript array

1.6k Views Asked by At

I'm trying to visualize data retrieved from a JSON file in a REST api. I'm using Morris js to create a simple bar chart. I'm having a hard time figuring out how to properly format the javascript array.

The chart is generated like this:

Morris.Bar({
    element: 'myfirstchart',
    data: [
        { year: '2008', value: 20 },
        { year: '2009', value: 10 },
        { year: '2010', value: 5 },
        { year: '2011', value: 5 },
        { year: '2012', value: 20 }
    ],
    xkey: 'year',
    ykeys: ['value'],
    labels: ['Series A']
});

I have been trying to save values from JSON structure in a variable:

var USD = data.d.results[0].ExchangeCross;
var USD2 = data.d.results[0].ApprovedRate;

In order to add them to the chart i tried adding them to an array like this:

var obj = { year: USD, value: USD2 };

And then change data:[] to data:obj. This does not work. The optimal solution would be to run a each function for all the values i need, and then plot them into the chart.

Edit forEach function:

$( document ).ready(function() {
    $.ajax({
        url: "http://intra.site.com/_vti_bin/ListData.svc/ExchangeRates?$orderby=Modified%20desc",
        headers: { 'accept': 'application/json;odata=verbose', 'content-type': 'application/json;odata=verbose'},
        success: function(data){ 
                    var params = {
                        element: 'myfirstchart',
                        data: [],
                        xkey: 'year',
                        ykeys: ['value'],
                        labels: ['Series A']
                                    };

                        var data = JSON.parse(data);

                        data.d.results.forEach(function(element) {
                        var obj = { "year": element.ExchangeCross, "value": element.ApprovedRate }; 
                        params.data.push(obj);
                    });

                    Morris.Bar(params);

                                }  
            });
     });
2

There are 2 best solutions below

4
On BEST ANSWER

You have to load data received as JSON from API into your Morris chart. You do that by looping thru your JSON, creating an object and pushing those into an array.

Assuming that this is the JSON that you receive:

var jsonString = '{"d": {"results": [{"ExchangeCross": "2010", "ApprovedRate": "20"}, {"ExchangeCross": "2011", "ApprovedRate": "5"}, {"ExchangeCross": "2012", "ApprovedRate": "15"}, {"ExchangeCross": "2013", "ApprovedRate": "35"}, {"ExchangeCross": "2014", "ApprovedRate": "10"}]}}';

Create a params object to use with your Morris chart, with data as an empty array:

var params = {
    element: 'myfirstchart',
    data: [],
    xkey: 'year',
    ykeys: ['value'],
    labels: ['Series A']
};

Parse your JSON (if you have a string):

var data = JSON.parse(jsonString);

Iterate through the results array which is wrapped inside a d, create a compatible object with the values you need and push that object into the params.data array:

data.d.results.forEach(function(element) {
    var obj = { "year": element.ExchangeCross, "value": element.ApprovedRate }; 
    params.data.push(obj);
});

Call your Morris.Bar with params:

Morris.Bar(params);

.

2
On

If I understand you, you're trying to replace the data part of the JS object that you're passing to the Morris Bar function?

You need to create an array not an object.

Try something like this:

var USD = data.d.results[0].ExchangeCross;
var USD2 = data.d.results[0].ApprovedRate;

var dataArray = [];

// push each item into the array
dataArray.push( {year: USD, value: USD2} );

Morris.Bar({
    element: 'myfirstchart',
    data: dataArray,
    xkey: 'year',
    ykeys: ['value'],
    labels: ['Series A']
});