Skip to content

Group array to an object in javascript

Hello apologies if this has been asked before but I can’t search for the right term to find something useful.

Suppose if I had an array of

[
 "0.001234", "2021-07-14 08:24:30"
 "0.001245", "2021-07-14 01:04:24"
 // etc etc ...
]

how would I change this to an object like so?

{
 0: ["0.001234", "2021-07-14 08:24:30"]
 1: ["0.001245", "2021-07-14 01:04:24"]
 // etc etc ...
}

Answer

Edit – just noticed the format of your data – map reduce may not work for you, but still a similar principle:

let objForm = {}
for (let idx=0; idx<arrayForm.length; idx+=2) {
  objForm[idx/2] = [ arrayForm[idx], arrayForm[idx+1] ]
}

Old answer:

You can use a reduce pattern.

let arrayForm = ["one", "two"]
let objForm = arrayForm.reduce((acc, val, idx) => ({
  ...acc,
  [idx]: val
}), {})
console.log(objForm) // { 0: "one", 1: "two" }

The reduce method gets the accumulated value, the current value and the array index. In this case we are using the spread operator to add the next value to the object.

Note that the ( before the object definition is needed, so that JS doesn’t confuse it with a code block.