Here is the list of JavaScript objects that I am working with:
var filtered = [
{'faculty': 'Faculty of Sciences',
'degree': 'bachelor',
'majorName': 'Computer Science'},
{'faculty': 'Faculty of Sciences',
'degree': 'bachelor',
'majorName': 'Business Computing'},
{'faculty': 'Faculty of Sciences',
'degree': 'masters',
'majorName': 'Computer Science'},
{'faculty': 'Faculty of Sciences',
'degree': 'masters',
'majorName': 'Business Computing'},
{'faculty': 'School of Arts',
'degree': 'bachelor',
'majorName': 'Graphic Design'},
{'faculty': 'School of Arts',
'degree': 'bachelor',
'majorName': 'Media and Communication'},
{'faculty': 'School of Arts',
'degree': 'masters',
'majorName': 'Musicology'},
{'faculty': 'School of Arts',
'degree': 'masters',
'majorName': 'Media'}]
I would like to convert it to a list of nested objects by grouping on faculty and then degree.
Please run this to see what my current result is:
var filtered = [{
'faculty': 'Faculty of Sciences',
'degree': 'bachelor',
'majorName': 'Computer Science'
},
{
'faculty': 'Faculty of Sciences',
'degree': 'bachelor',
'majorName': 'Business Computing'
},
{
'faculty': 'Faculty of Sciences',
'degree': 'masters',
'majorName': 'Computer Science'
},
{
'faculty': 'Faculty of Sciences',
'degree': 'masters',
'majorName': 'Business Computing'
},
{
'faculty': 'School of Arts',
'degree': 'bachelor',
'majorName': 'Graphic Design'
},
{
'faculty': 'School of Arts',
'degree': 'bachelor',
'majorName': 'Media and Communication'
},
{
'faculty': 'School of Arts',
'degree': 'masters',
'majorName': 'Musicology'
},
{
'faculty': 'School of Arts',
'degree': 'masters',
'majorName': 'Media'
}
]
var grouped = _.mapValues(_.groupBy(filtered, 'faculty'),
flist => flist.map(filtered => _.omit(filtered, 'faculty')));
_.forEach(grouped, function(value, key) {
grouped[key] = _.groupBy(grouped[key], function(item) {
return item.degree;
});
});
console.log(grouped);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>
How can I omit the "degree" property that is left behind? And keep the values of "majorName" property in a list belonging to the generated degree property?
End result could be something like this:
{
"Faculty of Sciences": {
"bachelor": ["Computer Science", "Business Computing"],
"masters": ["Computer Science", "Business Computing"]
},
"School of Arts": {
"bachelor": ["Graphic Design", "Media and Communication"],
"masters": ["Musicology", "Media"]
}
}
Thank you :)