3

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

2
  • 1
    not sure what your asking for here, your "what I want" is an array of objects. Commented Dec 6, 2015 at 13:12
  • Sure, what I need is to 'destroy' the array '[{title: hi}, {title: ha}, {title: ho}]', else I will have two arrays of objects. Commented Dec 6, 2015 at 13:17

3 Answers 3

3

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/

Sign up to request clarification or add additional context in comments.

Comments

0
{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
});

3 Comments

Yes, I thought in it, but is it possible to update one time the database, and not n times for each object?
How are you inserting them? db.paises.insert() ?
Just with "$push" : { "paises" : array}
0

If you are using ES6 you can use spread operator.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.