Skip to content

Instantly share code, notes, and snippets.

@zmts
Last active November 23, 2020 22:25
Show Gist options
  • Select an option

  • Save zmts/aa5f2be9b89fce1f9c19c0017545c641 to your computer and use it in GitHub Desktop.

Select an option

Save zmts/aa5f2be9b89fce1f9c19c0017545c641 to your computer and use it in GitHub Desktop.
Reduce

Reduce

Objects array to object

const someObjectsArr = [{id: 1, name: 'alex'}, {id: 2, name: 'bob'}]
const objectsById = someObjectsArr.reduce((result, item) => {
  result[item.id] = item
  return result
}, {})

console.log(objectsById) // >>
{
  1: {id: 1, name: 'alex'}
  2: {id: 2, name: 'bob'}
}

Objects array to flat array

const someObjectsArr = [{id: 1, name: 'alex'}, {id: 2, name: 'bob'}]
const flatArray = someObjectsArr.reduce((acc, curr) => acc.concat(...Object.entries(curr)) , [])

console.log(flatArray) // >>
["id", 1, "name", "alex", "id", 2, "name", "bob"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment