Skip to content

Instantly share code, notes, and snippets.

@therealklanni
Created March 29, 2014 04:13
Show Gist options
  • Save therealklanni/9848249 to your computer and use it in GitHub Desktop.
Save therealklanni/9848249 to your computer and use it in GitHub Desktop.
Array of Objects distiller
// Found myself needing to do this the other day...
//
// Map an array of objects down to a single object in one pass
function distill (a, b) {
a[b.name] = b.value;
return a;
}
// Say you have objects that follow this format
var obj1 = {
name: 'blah',
value: 222
}
// And you want to combine them into a single object with this resulting format
mappedObj = {
blah: 222
}
// So let's make a couple more examples to test with
var obj2 = { name: 'barf', value: 888 }
var obj3 = { name: 'fleh', value: 999 }
var obj4 = { name: 'blah', value: 444 }
// Drop them into an array and run them through the reducer
[obj1, obj2, obj3, obj4].reduce(distill, {}) // <= note the {} param
// Produces:
{
barf: 888,
blah: 444,
fleh: 999
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment