I have a below object where I am trying to group data using department and sub department value. I have tried using reduce function on the department name but could not achieve the desired result.
For example, I have an array of department objects:
var arr = //Actual Object
[{
"department": "Admin",
"sub_department": [{
"name": "Finance",
"application": [{
"name": "F1",
"tag": 100
}]
}]
},
{
"department": "Admin",
"sub_department": [{
"name": "Registry",
"application": [{
"name": "R2",
"tag": 200
}]
}]
},
{
"department": "Admin",
"sub_department": [{
"name": "Finance",
"application": [{
"name": "F2",
"tag": 200
}]
}]
},
{
"department": "Helpdesk",
"sub_department": [{
"name": "Entry",
"application": [{
"name": "E1",
"tag": 200
}]
}]
}
]
//Tried below code
var result = arr.reduce(function(r, a) {
r[a.department] = r[a.department] || [];
r[a.department].push(a);
return r;
}, Object.create(null));
console.log(result)
And I am trying to achieve the desired result by grouping same department and if both department and sub_department.name is same then pushing the application into sub_department array.
[
{
"department": "Admin",
"sub_department": [
{
"name": "Finance",
"application": [
{
"name": "F1",
"tag": 100
},
{
"name": "F2",
"tag": 200
}
]
},
{
"name": "Registry",
"application": [
{
"name": "R2",
"tag": 200
}
]
}
]
},
{
"department": "Helpdesk",
"sub_department": [
{
"name": "Entry",
"application": [
{
"name": "E1",
"price": 200
}
]
}
]
}
]
Any help on this will be really helpful.