Issue
I have an array of objects in the below format
const Employer = [{'company': 'ABC','location': 'Phase 1','year': '2012'},
{'company': 'ABC','location': 'Phase2', 'year': '2013'},
{'company': 'XYZ','location': 'Phase3','year': '2012'}];
And expected output is
{
'ABC':{
'company': 'ABC',
data:[
{'location':'Phase1','year':2012},
{'location':'Phase2', 'year':2013}]
},
'XYZ':{
'company': 'ABC',
data:[
{'location':'Phase3','year':2012}]
}
}
What I have tried is
name = 'Angular';
groupedData:any;
ngOnInit(){
const Employer = [{'company': 'ABC','location': 'Phase 1','year': '2012'},
{'company': 'ABC','location': 'Phase2', 'year': '2013'},
{'company': 'XYZ','location': 'Phase3','year': '2012'}];
this.groupedData = _.mapValues(_.groupBy(Employer, 'company'))
console.log(this.groupedData)
}
}
Output:
{
"ABC": [
{
"company": "ABC",
"location": "Phase 1",
"year": "2012"
},
{
"company": "ABC",
"location": "Phase2",
"year": "2013"
}
],
"XYZ": [
{
"company": "XYZ",
"location": "Phase3",
"year": "2012"
}
]
}
Here again I need to group the data. Can anyone help me to get the expected output
Solution
const Employers = [{ 'company': 'ABC', 'location': 'Phase 1', 'year': '2012' },
{ 'company': 'ABC', 'location': 'Phase2', 'year': '2013' },
{ 'company': 'XYZ', 'location': 'Phase3', 'year': '2012' }];
const output: any = {};
for (const e of Employers) {
if (output[e.company]) {
output[e.company].data.push({ location: e.location, year: e.year });
} else {
output[e.company] = { company: e.company, data: [{ location: e.location, year: e.year }] };
}
}
console.log(output);
Answered By - zainhassan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.