Используя ES6 и Object.entries
, вы можете сделать что-то вроде:
const obj = {
'User 1': [
{ count: '1', stage: 'A', jCount: '10', name: 'User 1', stageId: 'A1' },
{ count: '8', stage: 'B', jCount: '10', name: 'User 1', stageId: 'B1' }
],
'User 2': [
{ count: '7', stage: 'C', jCount: '8', name: 'User 2', stageId: 'C1' },
{ count: '8', stage: 'B', jCount: '8', name: 'User 2', stageId: 'B1' },
{ count: '9', stage: 'A', jCount: '8', name: 'User 2', stageId: 'A1' },
{ count: '8', stage: 'D', jCount: '8', name: 'User 2', stageId: 'D1' }
],
'User 3': [
{ count: '6', stage: 'D', jCount: '6', name: 'User 3', stageId: 'D1' },
{ count: '8', stage: 'B', jCount: '6', name: 'User 3', stageId: 'B1' },
{ count: '1', stage: 'A', jCount: '6', name: 'User 3', stageId: 'A1' }
]
/* Many more users */
};
const stages = ['A1', 'B1', 'C1', 'D1'];
const getCount = (stage, user) => {
const stageItem = obj[user.name].find(s => s.stageId === stage);
return stageItem ? stageItem.count : 0;
};
const r = Object.entries(obj)
.map(([name, user]) => ({ name, jCount: user[0].jCount }))
.map(user => {
const stagesCounts = stages
.map(stage => ({
[`stageIdCount${stage}`]: getCount(stage, user)
}))
.reduce((acc, stage) => ({ ...acc, ...stage }), {});
return { ...user, ...stagesCounts };
});
console.log(r);
Обновление (ES5)
const obj = {
'User 1': [
{ count: '1', stage: 'A', jCount: '10', name: 'User 1', stageId: 'A1' },
{ count: '8', stage: 'B', jCount: '10', name: 'User 1', stageId: 'B1' }
],
'User 2': [
{ count: '7', stage: 'C', jCount: '8', name: 'User 2', stageId: 'C1' },
{ count: '8', stage: 'B', jCount: '8', name: 'User 2', stageId: 'B1' },
{ count: '9', stage: 'A', jCount: '8', name: 'User 2', stageId: 'A1' },
{ count: '8', stage: 'D', jCount: '8', name: 'User 2', stageId: 'D1' }
],
'User 3': [
{ count: '6', stage: 'D', jCount: '6', name: 'User 3', stageId: 'D1' },
{ count: '8', stage: 'B', jCount: '6', name: 'User 3', stageId: 'B1' },
{ count: '1', stage: 'A', jCount: '6', name: 'User 3', stageId: 'A1' }
]
/* Many more users */
};
const stages = ['A1', 'B1', 'C1', 'D1'];
function getCount(stage, user) {
const stageItem = obj[user.name].find(s => s.stageId === stage);
return stageItem ? stageItem.count : 0;
}
function mapStages(user) {
return stages
.map(stage => ({
[`stageIdCount${stage}`]: getCount(stage, user)
}))
.reduce((acc, stage) => ({ ...acc, ...stage }), {});
}
const r = Object.entries(obj)
.map(function(entry) {
return { name: entry[0], jCount: entry[1][0].jCount };
})
.map(function(user) {
return Object.assign(user, mapStages(user));
});
console.log(r);