Created
March 29, 2014 04:13
-
-
Save therealklanni/9848249 to your computer and use it in GitHub Desktop.
Array of Objects distiller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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