provsalt
provsalt

Reputation: 13

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 ...
}

Upvotes: 0

Views: 50

Answers (2)

Fabio Torchetti
Fabio Torchetti

Reputation: 206

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.

Upvotes: 1

Andy
Andy

Reputation: 63524

Create a new object and then iterate over the array in element pairs and add them as a new array to the object.

const arr = [
 '0.001234', '2021-07-14 08:24:30',
 '0.001245', '2021-07-14 01:04:24'
];

const obj = {};

for (let i = 0;  i < arr.length; i += 2) {
  obj[i / 2] = [ arr[i], arr[i + 1] ];
}

console.log(obj);

Upvotes: 1

Related Questions