0

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!

4
  • 2
    [o1, o2]; _; <--- yeah, it uses underscore! Commented Mar 4, 2015 at 20:00
  • Do you not have a fixed number of variables/objects in order to do what you did in your question? and Alexander's answer? Is the issue flexibility? Commented Mar 4, 2015 at 20:02
  • they will keep coming in 1 at a time, so I'd like to continuously push into this new object array @SmokeyPHP Commented Mar 4, 2015 at 20:05
  • 1
    @ajmajmajma What's wrong with myArray.push(newObject) ? Commented Mar 4, 2015 at 20:05

3 Answers 3

3

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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]);
}

Comments

1

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"}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.