Given an array of objects:
var projects = [
{
id: 1,
name: 'Trader Portal'
},
{
id: 2,
name: 'Risk Engine'
},
];
What is the most elegant way of converting it into the following structure - essentially and array of the ids along with a map of the objects:
{
projects: [
1,
2
],
projectMap: {
1: {
id: 1,
name: 'Trader Portal'
},
2: {
id: 2,
name: 'Risk Engine'
}
}
}
I did this using underscore (see below or my codepen), but is there a better way? For example can this be done in a more declarative way using functional programming? Is there a way to genericize the code to work on an array of any type of objects?
var projects = [
{
id: 1,
name: 'Trader Portal'
},
{
id: 2,
name: 'Risk Engine'
},
];
var result = {};
result.projects = _.map(projects, function(project) {
return project.id;
});
result.projectMap = {};
_.each(projects, function(project) {
result.projectMap[project.id] = project;
});
console.log(JSON.stringify(result));