javascript - 将数据解析为 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 数据。
我想建立一个像 forC1
和C2
[[17,7,0],[0,13,11]]
C1 的第一个嵌套数组,其中第三个值为 0,因为对于0806
date,该值不存在。
C2 的第二个嵌套数组,其中第一个值为 0,因为对于0506
date,该值不存在。
请帮忙。我无法有效地形成阵列。
我认为这将是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);
}
}
});
});
解决方案
您可以制作一个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);
推荐阅读
- javascript - 如何连接烧瓶休息 API 输出以做出反应并显示结果
- reactjs - Firebase - getToken() 抛出不受支持的 MIME 类型
- python - AttributeError:“NoneType”对象没有属性“文本”+问题
- wordpress - Wordpress 登录到主页不是我的帐户
- python-3.x - 如何使用 sftp (paramiko) 获取远程主机上的文件大小并查看进度条?
- tensorflow - RStudio Tensorflow Keras flow_from_directory 问题
- firebase - 如何在使用 firebase/auth 和 react-native 验证用户的电子邮件后立即登录用户?
- r - 在数据框中复制带有条件的行而不循环
- python - 无法更新从现有列派生的行中的新列值,这些列具有多个由“,”分隔的值?
- firebase - 使用 onRequest 云函数参数中的调度表达式调度 cron 作业