当前位置: 代码迷 >> JavaScript >> JS 怎的将json格式数据写入数组
  详细解决方案

JS 怎的将json格式数据写入数组

热度:172   发布时间:2013-09-05 16:02:07.0
JS 怎样将json格式数据写入数组
json数据格式如下:
[{"day":"1969-12-31","sum":10},{"day":"1969-12-30","sum":20},{"day":"1969-12-29","sum":30},{"day":"1969-12-28","sum":15,{"day":"1969-12-27","sum":26},{"day":"1969-12-26","sum":33},{"day":"1969-12-25","sum":18}]

写入这样一个数组里:
var chartData = [
{
country: "12-25",
visits: 18,
color: "#FF0F00"
},
{
country: "12-26",
visits: 33,
color: "#FF0F00"
},
{
country: "12-27",
visits: 26,
color: "#FF0F00"
},
{
country: "12-28",
visits: 15,
color: "#FF0F00"
},
{
country: "12-29",
visits: 30,
color: "#FF0F00"
},
{
country: "12-30",
visits: 20,
color: "#FF0F00"
},
{
country: "12-31",
visits: 10,
color: "#FF0F00"
}];
 如何实现呢?
json js 数组

------解决方案--------------------

var json =  [{"day":"1969-12-31","sum":10},{"day":"1969-12-30","sum":20},{"day":"1969-12-29","sum":30},{"day":"1969-12-28","sum":15},{"day":"1969-12-27","sum":26},{"day":"1969-12-26","sum":33},{"day":"1969-12-25","sum":18}];
var chartData = [];
for(var i=json.length-1; i>=0 ; i--)
chartData.push({
country: json[i].day.replace(/^\d\d\d\d-/,""),
visits: json[i].sum,
color: "#FF0F00"
});


------解决方案--------------------
jquery  差不多意思,不好。

var json =  [{"day":"1969-12-31","sum":10},{"day":"1969-12-30","sum":20},{"day":"1969-12-29","sum":30},{"day":"1969-12-28","sum":15},{"day":"1969-12-27","sum":26},{"day":"1969-12-26","sum":33},{"day":"1969-12-25","sum":18}];
var chartData = [];
var obj={};
$(json.reverse()).each(function(i,e){
 obj.country=e.day.replace(/^\d\d\d\d-/,"");
 obj.visits=e.sum;
 obj.color="#FF0F00";
  chartData.push(obj);
});

------解决方案--------------------
  相关解决方案