我已经从数据库中的数据创建了一个对象数组。我想在饼图上绘制数据,但我在制作这种格式时遇到了困难。
以下是我到目前为止创建的最终结果:
let natinalityBreakdown = [
{Omani: Array(2), Pakistani: Array(2), Indian: Array(3), Test: Array(1)},
{Omani: Array(6), Chinese: Array(1)},
{Omani: Array(51), OMANi: Array(1), Pakistani: Array(5)}
];
使用以下代码:
let natinalityBreakdowna = [];
_.forEach(company, function(company) {
const linkedCompanyUsers= _(driver)
.filter(d => d.companyId === company.companyId)
.value();
console.log(linkedCompanyUsers);
let nationalityBreakdown = _.groupBy(linkedCompanyUsers, "nationality");
console.log(nationalityBreakdown);
nationalityBreakdown = _.omit(nationalityBreakdown, "undefined");
console.log(nationalityBreakdown);
natinalityBreakdowna.push(nationalityBreakdown);
});
console.log(natinalityBreakdowna);
我想在对象中输入如下结果:
{Omani: Array(59), Pakistani: Array(7), Indian: Array(3), Test: Array(1), Chinese: Array(1), OMANi: Array(1)}
由于
答案 0 :(得分:1)
您可以使用array#reduce
在对象中使用array#concat
在同一组中添加相同国籍的人。
var result = natinalityBreakdown.reduce(function(res, obj){
Object.keys(obj).forEach(function(k){
res[k] = res[k] || [];
res[k] = res[k].concat(obj[k]);
});
return res;
},{});