【问题标题】:Creating arrays out of objects in AngularJS在 AngularJS 中用对象创建数组
【发布时间】:2014-11-28 15:00:37
【问题描述】:

给定以下对象:

Object {November 2014: Object}
    November 2014: Object
        Cars: Object
            324: Object
                duration: 1417132808000
                total: "00:00:08"
                trips: 1
            369: Object
                duration: 5668531247000
                total: "00:00:47"
                trips: 4
            391: Object
                duration: 9919930257000
                total: "00:10:57"
                trips: 7
            396: Object
                duration: 9919929791000
                total: "00:03:11"
                trips: 7
            KE-22: Object
                duration: 5668531269000
                total: "00:01:09"
                trips: 4

我需要能够从从中提取的数据中创建数组。

类似这样的:

标签:(车内物体的钥匙) [324, 369, 391, 396, KE-22]

系列:(来自 Cars 中每个对象的属性) [Trips, Total]

数据:(来自 Cars 中每个对象的属性值)

[
    [1,4,7,7,4], // Array of trips for each car, in order.
    ["00:00:08", "00:00:47", "00:10:57", "00:03:11", "00:01:09"] // Array of total duration for each car, in order.
]

我打算用这个数组为每个月填充一个图表

对象集合已使用以下代码创建,可能与问题相关:

    var dataByMonth = _.groupBy($scope.recordlist, function(record) { 
        return moment(record.date, 'DD-MM-YYYY').format('MMMM YYYY'); 
    });

    dataByMonth = _.mapValues(dataByMonth, function(month) {
        var obj = {};
        obj.Cars = _.groupBy(month, 'car');
        obj.Drivers = _.groupBy(month, 'driver');

        _.each(obj, function(groupsValue, groupKey) {
            obj[groupKey] = _.mapValues(groupsValue, function(groupValue) {
                return _.reduce(groupValue, function(sum, trip) {
                    sum['trips']++;
                    sum['duration']+= moment.utc(trip.duration, 'HH:mm:ss');
                    sum['total'] = moment.utc(sum.duration). format('HH:mm:ss')
                    return sum;
                }, {trips: 0, duration: 0, total:0})
            });
        })

        return obj;
    });

    $scope.statistics = dataByMonth;
    console.log($scope.statistics);

关于如何进行的任何提示?

【问题讨论】:

    标签: arrays angularjs lodash


    【解决方案1】:
    _.chain(cars).pairs().map(function(p) {
      var id = p[0];
      return [id].concat(_.values(p[1])); // produces an array of [{id, duration, trips, total}]
    }).reduce(function(acc, as) { 
      // we assume properties are sorted
      return _.map(as, function(a, i) { 
        return acc[i] = (acc[i] || []).concat([a]); 
      }); 
    }, []).value();
    

    【讨论】:

      【解决方案2】:

      对象的一个​​问题是它们不能保证其属性的顺序。

      这意味着在转换为数组之前,您需要以某种方式决定预定义的序列算法。在下面的代码中,这是属性名称的字母数字顺序。

      var objPart = obj["November 2014"]["Cars"];
      var ret = _.chain(objPart).transform(function(total, n , key){
          //In this first iteration we collect all possible series that may exist,
          total.series =_.union(total.series, _.keys(n) );
          //and all labels
          total.labels.push(key);
      }, {labels:[], series:[], data:[]} ).mapValues(function(val){
          //sorting labels, series. Data do not yet exist
          return _.sortBy(val);
      }).value();
      
      //based on the above orders generate a multi dimensional array for data.
      ret = _.transform(ret.labels, function(total, lbl){
          var arr = _.transform(ret.series, function(partialTotal, ser){
              partialTotal.push(objPart[lbl][ser]);
          }, []);
          total.data.push(arr);
      }, ret);
      
      console.log("Labels:",ret.labels);
      console.log("Series:",ret.series);
      console.log("Data:",JSON.stringify(ret.data));
      

      上述解决方案甚至适用于以下数据:

      var obj = {
          "November 2014": {
              "Cars": {
                  "339": {
                      "trips": 1,
                      "total": "00:00:08",
                      "duration": 1417132809000,
                  },            
                  "324": {
                      "trips": 1,
                      "extraProp1":"x",
                      "total": "00:00:08",
                      "duration": 1417132808000,
      
                  },
                  "369": {
                      "duration": 5668531247000,
                      "trips": 4,
                      "total": "00:00:47",
                      "extraProp2":"y"
                  },
                  "391": {
                      "duration": 9919930257000,
                      "trips": 7,
                      "total": "00:10:57"
                  },
                  "396": {
                      "duration": 9919929791000,
                      "total": "00:03:11",
                      "trips": 7
                  },
                  "KE-22": {
                      "duration": 5668531269000,
                      "total": "00:01:09",
                      "trips": 4
                  }
              }
          }
      }
      

      输出:

      Labels: ["324", "339", "369", "391", "396", "KE-22"]
      Series: ["duration", "extraProp1", "extraProp2", "total", "trips"]
      Data: [[1417132808000,"x",null,"00:00:08",1],
      [1417132808000,null,null,"00:00:08",1],
      [5668531247000,null,"y","00:00:47",4],
      [9919930257000,null,null,"00:10:57",7],
      [9919929791000,null,null,"00:03:11",7],
      [5668531269000,null,null,"00:01:09",4]]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-22
        • 1970-01-01
        • 2017-09-02
        • 1970-01-01
        • 2016-05-13
        • 2016-12-15
        相关资源
        最近更新 更多