Javier
Javier

Reputation: 33

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

Upvotes: 3

Views: 134

Answers (3)

Kunal Kapadia
Kunal Kapadia

Reputation: 3333

If you are using ES6 you can use spread operator.

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

Upvotes: 0

kockburn
kockburn

Reputation: 17616

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

This is not object of objects. These are just objects.

If what you want is a way to handle each object one by one and insert them into your database you could do something like this.

[{title: hi}, {title: ha}, {title: ho}].forEach(function(obj){
  //do something with object
});

Upvotes: 0

Gabriel Cuenca
Gabriel Cuenca

Reputation: 121

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/

Upvotes: 3

Related Questions