Skip to content

Instantly share code, notes, and snippets.

@katylava
Last active October 5, 2018 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save katylava/c66bed5dfbc6b01d802a4fca3f56a76f to your computer and use it in GitHub Desktop.
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
// 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