1

hello i have json response from MySql in this format

{
    "allResult": [{
        "UkupanBroj": "1",
        "mesec": "Jul"
    }, {
        "UkupanBroj": "3",
        "mesec": "Jun"
    }, {
        "UkupanBroj": "1",
        "mesec": "May"
    }],
    "resultByKurs": null
}

I am trying to create from this response object to pass into chart plugin

var flotDashSales2Data = [{
    data: [
        ["Jan", 240],
        ["Feb", 240],
        ["Mar", 290],
        ["Apr", 540],
        ["May", 480],
        ["Jun", 220],
        ["Jul", 170],
        ["Aug", 190]
    ],
    color: "#850d0d"
}];

Is it possible to create new object from my response??? In this way in would be cool if i dont have in my response some month to set form example ["Jan", 0] in my data wich i pass to plugin?

1
  • Can you confirm that you want the value of "UkupanBroj" as the second value in the month pairs.... e.g. {"UkupanBroj":"123","mesec":"Jul"} maps to ["Jul", 123] ? Commented Jun 22, 2015 at 11:38

2 Answers 2

5

You can get the actual data with:

data_result = JSON.parse(result);

It will not have the same format but you'll be able to transform it into what you need.

To aggregate the data you could do something along these lines:

var aggregate = {
    "Jan": 0,
    "Feb": 0,
    "Mar": 0,
    "Apr": 0,
    "May": 0,
    "Jun": 0,
    "Jul": 0,
    "Aug": 0 // fill in all 12 months
};

for (i = 0; i < data_result.allResult.length; i++)
{
    item = data_result.allResult[i];
    aggregate[item.mesec] += parseInt(item.UkupanBroj, 10);
}

Then, fill the array with the aggregate data:

lotDashSales2Data = [{
    data: [
        ["Jan", aggregate.Jan],
        ["Feb", aggregate.Feb],
        ["Mar", aggregate.Mar],
        ["Apr", aggregate.Apr],
        // ... all 12 months
    ],
    color: "#850d0d"
}];

EDIT: because you have the invariant of 12 months (they will never change) you can avoid complex code by simply listing them one by one as shown in my code. If you prefer more complex code, instead, it can be solved that other way, to. It is more a matter of choice and trade-offs (flexibility vs readability). Other factors such as performance should be irrelevant.

Sign up to request clarification or add additional context in comments.

Comments

0
var flotDashSales2Data = JSON.parse(response);

use JSON.parse

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.