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"
}];
如何实现呢?
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" });
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); });
var obj={};放到function(i,e)里边,不然所有数组元素中都是同一个对象
JavaScript code?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 = []; $(json.reverse()).each(function(i,e){ var obj={}; obj.country=e.day.replace(/^\d\d\d\d-/,""); obj.visits=e.sum; obj.color="#FF0F00"; chartData.push(obj); });