Question

I have a following JSON:

sales = {
  "February 20, 2014": {
    "services": 0,
    "total": 160,
    "repairs": 0
  },
  "February 18, 2014": {
    "services": 360,
    "total": 1109.95,
    "repairs": 410
  }
};

Now, this JSON has the data I want to graph. I already implemented nice d3.js chart, but I have issues getting data from that JSON to the chart. I need to somehow iterate through the JSON, and construct three arrays for services, total, repairs, and have them contain key value pairs, {x: date, y: value}.

So, the process would be something like this (pseudocode):

for date in sales
   services.push({x: date, y: services_value})
   total.push({x: date, y: total_value})
   repairs.push({x: date, y: repairs_value})
endfor

And the result for, lets say services, based on the sample json above, would be like this:

total = [{x: "February 20, 2014", y: "160.0"}, {x: "February 18, 2014", y: "1109.95.0"}]

As I am rendering this on the website, I need this implementation in Javascript.

Was it helpful?

Solution

Simple as it is (tuples of values):

var services = [];
var total = [];
var repairs = [];

for(i in sales) {
    services.push([i, sales[i].services]);
    total.push([i, sales[i].total]);
    repairs.push([i, sales[i].repairs]);
}

fiddle: http://jsfiddle.net/f3CKQ/1/

and if you need the exact structure as you have mentioned then:

var services = [];
var total = [];
var repairs = [];

for(i in sales) {
    var obj = {x: "", y: ""};
    obj.x = i;

    obj.y = sales[i].services;
    services.push(obj);

    obj.y = sales[i].total;
    total.push(obj);

    obj.y = sales[i].repairs;
    repairs.push(obj);
}

OTHER TIPS

In addition to Matus Dubrava's answer, you should always be sure to use hasOwnProperty() in this style of for loop to avoid iterating over members inherited from the object prototype.

var services = [];
var total = [];
var repairs = [];

for(i in sales) {
    if (sales.hasOwnProperty(i))
        continue;
    services.push(sales[i].services);
    total.push(sales[i].total); 
    repairs.push(sales[i].repairs);
}

Some browsers will actually iterate over inherited members like .length and .push

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top