Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array of objects to object of objects

What I have:

[{title: hi}, {title: ha}, {title: ho}]

What I want:

{title: hi}, {title: ha}, {title: ho}

This is because, when I try to add the array to a database, like:

"$push" : { "paises" : array}

, it will be:

Array of objects

But I want this:

Object of objects

like image 546
Javier Avatar asked May 26 '26 11:05

Javier


1 Answers

The solution:

var array = [{title: 'hi'}, {title: 'ha'}, {title: 'ho'}];

var object = {};

var arrayToObject = function(array, object){
  array.forEach(function(element, index){
    object[index] = element;
  })
  console.log(object);
}

arrayToObject(array, object);

https://jsfiddle.net/2r903tdh/

like image 149
Gabriel Cuenca Avatar answered May 30 '26 04:05

Gabriel Cuenca