Last active
October 5, 2018 14:50
-
-
Save katylava/c66bed5dfbc6b01d802a4fca3f56a76f to your computer and use it in GitHub Desktop.
convert array of name/value objects to a single object with with matching name/value properties
This file contains hidden or 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
// we have an array of objects, | |
var myArray = [ { name: 'a', value: 1 }, { name: 'b', value: 2 }, { name: 'c', value: 3 } ]; | |
// we want an object like { a: 1, b: 2, c: 3 } | |
// accumulator is an object, we'll set it to an empty object | |
// initially, when we call the reducer | |
// currentValue is the value of the current array element. | |
function reducer(accumulator, currentValue) { | |
accumulator[currentValue.name] = currentValue.value; | |
} | |
var myObj = myArray.reduce(reducer, {}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment