ajmajmajma
ajmajmajma

Reputation: 14226

Turn multiple separate objects into 1 array of objects

I have the two Hash objects.

One:

{"name" : "one" , "color" : "red" } 

Two:

{"name" : "two" , "color" : "blue" } 

I am trying to take those two objects and turn them into something looking like this:

[{"name" : "one" , "color" : "red" }, {"name" : "two" , "color" : "blue" } ]

How can I achieve this with javascript?

I'm also using underscore.

Also - When i have new object, I will receive more single objects I would like to push in like -

Three :   {"name" : "three" , "color" : "red" } 

Result being -

 Result :        [{"name" : "one" , "color" : "red" }, {"name" : "two" , "color" : "blue" }, {"name" : "three" , "color" : "red" } ]

Thanks!

Upvotes: 0

Views: 49

Answers (3)

Andrew Hendrie
Andrew Hendrie

Reputation: 6415

Try this:

var one = {"name" : "one" , "color" : "red" }; 
var two = {"name" : "two" , "color" : "blue" };
var array = [one, two];

Or use push like so:

var array = [];
array.push(one);
//array is now equal to [one]
array.push(two);
//array is now equal to [one,two]

Or use unshift like this:

var array = [];
array.unshift(one);
// array is now equal to [one]
array.unshift(two);
// array is now equal to [two, one]  

Essentially you just need to create variables to capture your Hash object values and use the variables you created to create an array.

You can additional values you can do this:

var three = {"name" : "three", "color" : "red" };
var array.push(three);

To display all values:

for (var i = 0; i < array.length; i++) {
    console.log(array[i]);
}

Upvotes: 2

Oleksandr T.
Oleksandr T.

Reputation: 77522

var a = {"name" : "one" , "color" : "red" }; 
var b = {"name" : "two" , "color" : "blue" };
var res = [a, b];
console.log(res);

or use push like so

var res = [];
res.push(a);
res.push(b);

Upvotes: 3

Kalle Bj&#246;rklid
Kalle Bj&#246;rklid

Reputation: 655

If you have an unkonwn number of objects, you'd use thepush function of array:

var res = [];
var one = {"name" : "one" , "color" : "red" }; 
var two = {"name" : "two" , "color" : "blue" };
res.push(one);
res.push(two);
// res is now: [{"name" : "one" , "color" : "red" }, {"name" : "two" , "color" : "blue" }]
res.push({"name" : "three"});
// res is now: [{"name" : "one" , "color" : "red" }, {"name" : "two" , "color" : "blue" }, {"name" : "three"}]

Upvotes: 1

Related Questions