首页 > 解决方案 > 将数据解析为 JavaScript 数组

问题描述

我有一个来自后端的数组数据格式,如下所示:

Array

[{"ckey::"C1","date":"0506","rows":17},
 {"ckey::"C1","date":"0706","rows":7},
 {"ckey::"C2","date":"0706","rows":13},
 {"ckey::"C2","date":"0806","rows":11}]

所以几天有 C1 数据,几天有 C2 数据。只有一天有 C1 和 C2 数据。

我想建立一个像 forC1C2

[[17,7,0],[0,13,11]]

C1 的第一个嵌套数组,其中第三个值为 0,因为对于0806date,该值不存在。

C2 的第二个嵌套数组,其中第一个值为 0,因为对于0506date,该值不存在。

请帮忙。我无法有效地形成阵列。

我认为这将是O(n^3)解决方案。但请帮忙。

更新

这是我的方法,我无法在此处发布代码,但它看起来像这样。

我进入date values了单独的数组,我过滤了独特的日子。

        angular.forEach(data, function(obj){
            if(timeData.indexOf(obj.date) === -1)
                timeData.push(obj.date);
        });

然后 ckey数组_distinctckeyArray也包含值[“C1”,“C2”]。

angular.forEach(_distinctckeyArray,function(_ckey){
     var _formattedDataArrItem = [];
     angular.forEach(timeData,function(_dateTimeString) {
         var _tempDataVolume = [];

            angular.forEach(_data,function(_dataObj) {
                 if(_dataObj.date === _dateTimeString) {
                     if(_dataObj.ckey === _ckey) {
                         _tempDataVolume.push(_dataObj.rows);

                     }else {
                         _tempDataVolume.push(0);

                     }
                 }
             });
         });

标签: javascriptarrays

解决方案


您可以制作一个dates具有日期属性的对象。将值初始化为0

reduce对数组进行分组。用于Object.values将对象转换为数组。

let arr = [{ckey:"C1","date":"0506","rows":17},{ckey:"C1","date":"0706","rows":7},{ckey:"C2","date":"0706","rows":13},{ckey:"C2","date":"0806","rows":11}];

//Make an object with property dates. assign all property to 0 as initial value.
//Expected output:
//{"0506":0,"0706":0,"0806":0}
let dates = arr.reduce((c, v) => Object.assign(c, {[v.date]: 0}), {});

//Loop thru the array using `reduce`. 
//This is to group the array to object using the ckey as the key
//After grouping, use `Object.values` to convert the object into array
let result = Object.values(arr.reduce((c, {ckey,date,rows}) => {
  c[ckey] = c[ckey] || { ...dates };   //Check if c[ckey] exist. If it does not, "clone" the dates object.
  c[ckey][date] = rows;                //Overide the initial value 0 to the rows value
  return c;
}, {})).map(o => Object.values(o));

console.log(result);


推荐阅读