Underscore Map and Pluck examples
Shows minor use of underscore's map and pluck methods to help sort through objects or arrays.
by Riffic
HTML
<script src="https://raw.github.com/documentcloud/underscore/master/underscore-min.js"></script>
JavaScript
var dataOne = {
foo: 'test1',
bar: 'test2'
},
dataTwo = {
foo: 'test3',
bar: 'test4'
},
dataThree = {
foo: 'test5',
bar: 'test6'
},
dataFake = {
foo: 'test7',
noteThisVar: 'test8'
},
allData = [dataOne, dataTwo, dataThree, dataFake],
//using underscore with map
map = _.map(allData, function(data) {
return data.bar || null;
}),
//using underscore with pluck (More common for objects).
//Note if it doesn't exist in this case, it returns undefined rather than null
pluck = _.pluck(allData, 'bar');
console.log(map); //returns [test2, test4, test6, null]
console.log(pluck);