Javascript 将缺少的值添加到分组数据
这是对我的建议的后续行动。我从对象数组中按日期获取分组值。当我对值进行分组时,如果每天按日期对缺少的类型进行分组,我可以将度量值填写为0 这是我的阵列:Javascript 将缺少的值添加到分组数据,javascript,jquery,arrays,json,ecmascript-6,Javascript,Jquery,Arrays,Json,Ecmascript 6,这是对我的建议的后续行动。我从对象数组中按日期获取分组值。当我对值进行分组时,如果每天按日期对缺少的类型进行分组,我可以将度量值填写为0 这是我的阵列: arr = [ { "date": "2020-01-01", "metric": 32, "type": "Google" }, { "date": "2020-01-01", "met
arr = [
{
"date": "2020-01-01",
"metric": 32,
"type": "Google"
},
{
"date": "2020-01-01",
"metric": 24,
"type": "Bing"
},
{
"date": "2020-01-02",
"metric": 1,
"type": "Google"
},
{
"date": "2020-01-02",
"metric": 32,
"type": "Jeeves"
},
{
"date": "2020-01-03",
"metric": 24,
"type": "Bing"
},
{
"date": "2020-01-03",
"metric": 30,
"type": "Google"
}
]
以下是我对数据进行分组的方式:
const groupBy = (array, key) => {
return array.reduce((result, currentValue) => {
(result[currentValue[key]] = result[currentValue[key]] || []).push(currentValue);
return result;
}, {});
};
const personGroupedByColor = groupBy(arr, 'date');
我的结果是:
2020-01-01:
0: {date: "2020-01-01", metric: 32, type: "Google"}
1: {date: "2020-01-01", metric: 24, type: "Bing"}
2020-01-02:
0: {date: "2020-01-02", metric: 1, type: "Google"}
1: {date: "2020-01-02", metric: 32, type: "Jeeves"}
2020-01-03:
0: {date: "2020-01-03", metric: 24, type: "Bing"}
1: {date: "2020-01-03", metric: 30, type: "Google"}
我有什么办法可以得到:
2020-01-01:
0: {date: "2020-01-01", metric: 32, type: "Google"}
1: {date: "2020-01-01", metric: 24, type: "Bing"}
2: {date: "2020-01-01", metric: 0, type: "Jeeves"}
2020-01-02:
0: {date: "2020-01-02", metric: 1, type: "Google"}
1: {date: "2020-01-02", metric: 0, type: "Bing"}
2: {date: "2020-01-02", metric: 32, type: "Jeeves"}
2020-01-03:
0: {date: "2020-01-03", metric: 30, type: "Google"}
1: {date: "2020-01-03", metric: 24, type: "Bing"}
2: {date: "2020-01-03", metric: 0, type: "Jeeves"}
我可以用度量值0替换缺少的值吗?您可以创建所有不同
类型
值的集合
,然后迭代personGroupedByColor
中的每个值,检查它们是否具有所有不同的类型
值,如果没有,推送具有该类型和度量值0
的新对象:
arr=[{
“日期”:“2020-01-01”,
“公制”:32,
“类型”:“谷歌”
},
{
“日期”:“2020-01-01”,
“公制”:24,
“类型”:“必应”
},
{
“日期”:“2020-01-02”,
“公制”:1,
“类型”:“谷歌”
},
{
“日期”:“2020-01-02”,
“公制”:32,
“类型”:“Jeeves”
},
{
“日期”:“2020-01-03”,
“公制”:24,
“类型”:“必应”
},
{
“日期”:“2020-01-03”,
“公制”:30,
“类型”:“谷歌”
}
]
常量groupBy=(数组,键)=>{
返回数组.reduce((结果,当前值)=>{
(结果[currentValue[key]]=result[currentValue[key]]| |[])。推送(currentValue);
返回结果;
}, {});
};
让personGroupedByColor=groupBy(arr,'date');
常量类型=新集合(arr.map(a=>a.type));
for(按颜色分组的a){
types.forEach(t=>{
如果(!personGroupedByColor[a].some(v=>v.type==t)){
personGroupedByColor[a]。推送({
“日期”:personGroupedByColor[a][0]。日期,
“公制”:0,
“类型”:t
});
}
})
}
console.log(personGroupedByColor)代码>为什么要使用指标
0?我认为输出已经是正确的。当我创建堆叠柱形图时,它不能准确地绘制图表