生成数组的数组



我有一个返回JSON的Web-API方法,我希望数组结构看起来像这样:[ [123, 1.1], [222, 3.9] ]

我的Web API控制器以以下格式返回JSON:[{"CreatedDate":1314736440,"Reading":20.0}, "CreatedDate":1314779640,"Reading":7.9}]

Web API控制器:
[HttpGet]
 public HttpResponseMessage AllJson()
 {
     using (var ctx = new SomeContext())
     {
         var records = ctx.DataX.ToList();
         var dtos = Mapper.Map<...>(records);
         return new HttpResponseMessage
         {
             StatusCode = HttpStatusCode.OK,
             Content = new StringContent(JsonConvert.SerializeObject(dtos), Encoding.UTF8, "application/json")
         };
     }
 }

DTO

public class DtoModel
    {
        public int CreatedDate { get; set; }
        public double Reading { get; set; }
    }

示例Javascipt:

var seriesData = [];
        $.getJSON("api/xxx/AllJson ", function (data) {
            $.each(data, function (key, val) {
                seriesData.push(val.CreatedDate.toString() + " ," + val.Reading.toString());
                console.log(val.CreatedDate + " ," + val.Reading);
            });
        });

您需要创建一个包含多个长度为2的数组的单个数组。

请看下面的代码:

 $.getJSON("api/xxx/AllJson")
            .done(function (data) {
                var processedJson = new Array();
                $.map(data, function (obj, i) {
                    processedJson.push([obj.CreatedDate, obj.Reading]);
                });
                FunctionToDoSomethingWithYourDataStructure(processedJson);
            });

我想这也许能解决你的问题。在结构方面,它应该看起来像[[a,b],[c,d]];

var createSeriesData = function(){
    seriesData = [];
    JSON_obj = JSON.parse('[{"CreatedDate":1314736440,"Reading":20.0},{"CreatedDate":1314779640,"Reading":7.9}]');
    for(var key in JSON_obj){
        if(JSON_obj.hasOwnProperty(key)){
            seriesData[key] = [];
            seriesData[key].push(JSON_obj[key].CreatedDate.toString());
            seriesData[key].push(JSON_obj[key].Reading.toString());
        }
    }
    console.log(seriesData);
}

相关内容

  • 没有找到相关文章