我在JavaScript中有员工信息的数组结构
var emplyeeinfo=[{
empNo: 12302,
empId: '30984',
empJobCategory: 'Designer',
},
{
empNo: 14785,
empId: '33420',
empJobCategory: 'Associate Manager',
},
{
empNo: 13710,
empId: '32603',
empJobCategory: 'Designer',
},
{
empNo: 13783,
empId: '32675',
empJobCategory: 'Designer',
},
{
empNo: 15069,
empId: '33619',
empJobCategory: 'Designer',
},
{
empNo: 14285,
empId: '33020',
empJobCategory: 'Validator',
},
{
empNo: 14476,
empId: '33185',
empJobCategory: 'Designer',
}];
并希望根据以上信息构建数组
var employeejob=[{'Designer':[12302,13710,13783,15069,14476]},
{'Associate Manager':[14785]},
{'Validator':'[14285]}
];
我没有找到任何适当的机制来在JavaScript中构建这个数组,并且从这个数组想要为高图表系列构建以下数组
var finalchart={series:[7,5,1,1],
category:['Total','Designer','Associate Manager','Validator']};
答案 0 :(得分:3)
试试这个:
// Your new object
var obj = {};
// loop through the objects in array
employeeinfo.map(function(e){
// check if the object is already created or not
if(!obj[e.empJobCategory]){
// if not created then initialize it as an array
obj[e.empJobCategory] = [];
}
// push the new empNo in the created/present array
obj[e.empJobCategory].push(e.empNo);
});
// see the output
console.dir(obj);
<强> Working Fiddle 强>
也可以使用Array.reduce()
完成。
var obj = employeeinfo.reduce(function(p, c, i, a) {
if (!p[c.empJobCategory]) {
p[c.empJobCategory] = [];
}
p[c.empJobCategory].push(c.empNo);
return p;
}, {});
console.dir(obj);
<强> Working Fiddle 强>
答案 1 :(得分:0)
您可以尝试其他方式
function groupBy( array , f )
{
var groups = {};
array.forEach( function( o )
{
var group = JSON.stringify( f(o) );
groups[group] = groups[group] || [];
groups[group].push( o.empNo );
});
return Object.keys(groups).map( function( group )
{
return groups[group];
})
}
然后
var result = groupBy(employeeinfo, function(item)
{
return [item.empJobCategory];
});
印刷品
console.dir(result)