Skip to content

Instantly share code, notes, and snippets.

@HallexCosta
Last active May 30, 2021 04:38
Show Gist options
  • Save HallexCosta/5ffcc185ed832685c3095474ebc54dbe to your computer and use it in GitHub Desktop.
Save HallexCosta/5ffcc185ed832685c3095474ebc54dbe to your computer and use it in GitHub Desktop.
Array Values to Key-Value Pairs

Array Values to Key-Value Pairs

const arrayValues = ["blue", 1, "red", 4, "yellow", 2, "green", 7]

const arrayObjects = []

for (let i = 0; i < arrayValues.length; i += 2) {
  const newObject = {}
  const key = arrayValues[i]
  const value = arrayValues[i+1]
  newObject[key] = values
  arrayObjects.push(newObject)
}

// Output:
[
  {
    "blue": 1
  },
  {
    "red": 4
  },
  {
    "yellow": 2
  },
  {
    "green": 7
  }
]

References: https://stackoverflow.com/questions/42017674/convert-array-into-key-value-pairs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment