Read my book

I wrote books about Webpack and React. Check them out!

Wednesday, May 15, 2013

Extracting Object Property Values in JavaScript

There are times when you need to extract property values of object in JavaScript. This task is quite trivial to solve. It is also one of those cases that allows you to use functional composition effectively.

If I need to extract property values, I like to use a pattern looking like this:'name')). In this case our array (arr, matey) contains a bunch of objects names of which we want to extract. I've defined a helper, prop, for this purpose. prop is just a factory that returns a function that extracts the value. Consider the example implementation below:
function prop(name) {
    return function(o) {
        return o[name];
Who says factories are useful only in Java? :)

If you are using Underscore, you may find the pluck method useful. It does effectively the same thing.