Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Use Case

Fairly new to Lodash/Underscore. 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.

Code

Below is the current code I have. toHashMap appears much more readable, but less efficient. toMap seems to have the best efficiency at the expense of readability. jsfiddle

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'));

Question

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.

share|improve this question

1 Answer 1

up vote 3 down vote accepted

I think you are looking for _.indexBY

_.indexBy(data, 'rel');
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.