通过JSON迭代

时间:2014-04-02 21:50:56

标签: javascript json d3.js jinja2

我有以下JSON:

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

现在,这个JSON有我想要绘制的数据。我已经实现了很好的d3.js图表​​,但是我有问题从该JSON获取数据到图表。我需要以某种方式遍历JSON,并为服务,总计,修复构建三个数组,并使它们包含键值对{x: date, y: value}

所以,这个过程就像这样(伪代码):

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

结果,假设服务,基于上面的示例json,将是这样的:

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

当我在网站上呈现这个时,我需要在Javascript中实现这个实现。

2 个答案:

答案 0 :(得分:1)

简单(值的元组):

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]);
}

小提琴:http://jsfiddle.net/f3CKQ/1/

如果你需要你所提到的确切结构:

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);
}

答案 1 :(得分:0)

除了Matus Dubrava的回答之外,你应该总是确保在这种for循环风格中使用hasOwnProperty(),以避免迭代从对象原型继承的成员。

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);
}

有些浏览器实际上会对.length.push

等继承成员进行迭代