The use case is to convert an array of objects into a hash map where one property is the key and the other property is the value. Common case of using this is converting a "link" object in a hypermedia response into a hash map of links.
function toHashMap(data, name, value) {
return _.zipObject(_.pluck(data, name),
_.pluck(data, value));
}
function toMap(data, name, value) {
return _.reduce(data, function(acc, item) {
acc[item[name]] = item[value];
return acc;
}, {});
}
var data = [
{ rel: 'link1', href: 'url1'},
{ rel: 'link2', href: 'url2'},
{ rel: 'link3', href: 'url3'},
{ rel: 'link4', href: 'url4'},
];
console.log(toHashMap(data, 'rel', 'href'));
console.log(toMap(data, 'rel', 'href'));
toHashMap
appears much more readable, but less efficient. toMap
seems to have the best efficiency at the expense of readability.
Is there a more elegant solution - i.e. both readable and efficient? I suspect that Lodash might have a function to do this already, but I haven't found anything like this after looking at the API documentation.