我有一个来自后端的数组数据格式,如下所示:
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数据。
我想构建一个类似于C1
和C2
[[17,7,0],[0,13,11]]
C1的第一个嵌套数组,其中第三个值为0,因为对于0806
日期,该值不存在。
C2的第二个嵌套数组,其中第一个值为0,因为对于0506
日期,该值不存在。
请帮忙。我无法有效地形成阵列。
我认为这将是 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);
}
}
});
});
答案 0 :(得分:1)
您可以创建一个具有日期属性的对象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);
答案 1 :(得分:1)
我认为这就是你要找的东西。让我知道。
let data = [{
'ckey': 'C1',
'date': '0506',
'rows': 17
}, {
'ckey': 'C1',
'date': '0706',
'rows': 7
}, {
'ckey': 'C2',
'date': '0706',
'rows': 13
}, {
'ckey': 'C2',
'date': '0806',
'rows': 11
}]
function nested_arrays(array) {
const result = []
const obj = {
c1: [],
c2: []
}
for (let i = 0; i < array.length; i++) {
if (array[i].ckey === 'C1') {
obj.c1.push(array[i].rows)
}
if (array[i].ckey === 'C2') {
obj.c2.push(array[i].rows)
}
}
obj.c1.push(0) // set last value to 0
obj.c2.unshift(0) // set first value to 0
result.push(obj.c1, obj.c2)
return result
}
let _tempDataVolume = nested_arrays(data)
console.log(_tempDataVolume) //=> [ [ 17, 7, 0 ], [ 0, 13, 11 ] ]
答案 2 :(得分:1)
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}]
arr.map(res =>{
let c1arr = [],
let c2arr = [],
if(res.ckey== 'C1'){
c1arr.push(res.rows)
}else{ c2arr.push(res.rows) }
})
let newArrr = []
newArr.push(c1arr);
newArr.push(c2arr);
console.log('arr is',newArr)