Quantcast
Channel: Mohsen's Blog » admin
Viewing all articles
Browse latest Browse all 10

Underscore.js Deep Pluck Mixin

$
0
0

pluck() method is a convenience version of a common use case of map() that is fetching a property from a collection. I thought it would be great if we could use pluck() to access deeper objects and properties in a collection and made this mixin that make deep plucking possible:

_.mixin({
    pluck: function(obj, key) {
        if (key.indexOf(".") === -1) {
            return _.map(obj, function(value){ return value[key]; });
        }
        var keys = key.split(".").reverse();
        while(keys.length) {
            obj = _.pluck(obj, keys[keys.length - 1]);
            keys.pop();
        }
        return obj;
    }
});

Now it is easy to pluck a property from a collection that have a deep hierarchy

//Example
var myCollection = [
	{ a: { b: { c: { d: { e: { f: "first"  } } } } } },
	{ a: { b: { c: { d: { e: { f: "second" } } } } } },
	{ a: { b: { c: { d: { e: { f: "third"  } } } } } },
	{ a: { b: { c: { d: { e: { f: "forth"  } } } } } },
	{ a: { b: { c: { d: { e: { f: "fifth"  } } } } } },
	{ a: { b: { c: { d: { e: { f: "sixth"  } } } } } },
	{ a: { b: { c: { d: { e: { f: "seventh"} } } } } },
];

_(myCollection).pluck("a.b.c.d.e.f");
// returns:
["first", "second", "third", "forth", "fifth", "sixth", "seventh"]

Viewing all articles
Browse latest Browse all 10

Trending Articles