将对象数组拆分为数据和标签

时间:2018-03-04 16:08:30

标签: javascript

我有一个简单的JavaScript文件:

var prget = [{"datetime":"2017-10-29","count":36},    {"datetime":"2017-11-05","count":55},{"datetime":"2017-11-12","count":74},{"datetime":"2017-11-19","count":91},{"datetime":"2017-11-26","count":84},{"datetime":"2017-12-03","count":119},{"datetime":"2017-12-10","count":86},{"datetime":"2017-12-17","count":99},{"datetime":"2017-12-24","count":31},{"datetime":"2017-12-31","count":105},{"datetime":"2018-01-07","count":60},{"datetime":"2018-01-14","count":44},{"datetime":"2018-01-21","count":78},{"datetime":"2018-01-28","count":65},{"datetime":"2018-02-04","count":65},{"datetime":"2018-02-11","count":52},{"datetime":"2018-02-18","count":33},{"datetime":"2018-02-25","count":42}] 

我需要分成两个变量,一个是" datetime"价值,以及" count"值。

var prlabels = ["2017-10-29","2017-11-05","2017-11-12","2017-11-19","2017-11-26","2017-12-03","2017-12-10","2017-12-17","2017-12-24","2017-12-31","2018-01-07","2018-01-14","2018-01-21","2018-01-28","2018-02-04","2018-02-11","2018-02-18","2018-02-25"] 

var prdata = [36,55,74,91,84,119,86,99,31,105,60,44,78,65,65,52,33,42] 

我尝试了很多不同的方法而没有太大的成功,我非常喜欢初学者。我将如何实现这一目标?谢谢

3 个答案:

答案 0 :(得分:3)

使用地图功能

var datetimes = prget.map(d => d.datetime);
var counts = prget.map(d => d.count);

var dates= [];
var counts = [];

for (var i = 0; i < prget.length; i ++) {
    dates.push(prget[i].datetime);
    counts.push(prget[i].count);
}

答案 1 :(得分:0)

尝试以下内容。

// your code goes herefor (var key in p) {

var prget = [{"datetime":"2017-10-29","count":36},    {"datetime":"2017-11-05","count":55},{"datetime":"2017-11-12","count":74},{"datetime":"2017-11-19","count":91},{"datetime":"2017-11-26","count":84},{"datetime":"2017-12-03","count":119},{"datetime":"2017-12-10","count":86},{"datetime":"2017-12-17","count":99},{"datetime":"2017-12-24","count":31},{"datetime":"2017-12-31","count":105},{"datetime":"2018-01-07","count":60},{"datetime":"2018-01-14","count":44},{"datetime":"2018-01-21","count":78},{"datetime":"2018-01-28","count":65},{"datetime":"2018-02-04","count":65},{"datetime":"2018-02-11","count":52},{"datetime":"2018-02-18","count":33},{"datetime":"2018-02-25","count":42}] 
var date_array= [];
var count_array = [];

for (var key in prget) {
       if (key == 'datetime'){
          date_array.push(prget[key]);
       }
       if (key == 'count'){
         count_array.push(prget[key]);
       }

}
date_array.toString();
count_array.toString();

答案 2 :(得分:0)

使用es5语法:

var datetimes = prget.map(function(data) {
  return data.datetime;
});

var counts = prget.map(function(data) {
  return data.count;
});

如果您对高阶函数不熟悉,您也可以在常规for循环中执行此操作,如下所示:

var datatimes = [];
var counts = [];

for (var i = 0; i < prget.length; i++) {
  datatimes.push(prget[i].datatime);
  counts.push(prget[i].count);
}