2

I am trying to add a couple of arrays into one array in Javascript. It seems my way is not good enough. Let's suppose we have these three arrays as below:

var array_1 = [{"a" : 1, "b" : 2, "c" : 3}];
var array_2 = [{"d" : 4, "e" : 5, "f" : 6}];
var array_3 = new Array();

I would like to add array_1 and then array_2 into array_3. For instance, I want to make sure that array_1 is fully added first and then array_2 as below:

{"a" : 1, "b" = 2, "c" = 3"}
{"d" : 4, "e" = 5, "f" = 6"}

Could anyone please help me with this piece of code. Your help would be very much appreciated.

4
  • array_3.push(array1) - push array2 after? Commented Nov 20, 2013 at 22:43
  • See Array.prototype.concat Commented Nov 20, 2013 at 22:43
  • 2
    Is there any special reason why your arrays have just one element? Commented Nov 20, 2013 at 22:44
  • Do you need an array with 2 objects or 1 object with "a" through "f" keys? Commented Nov 20, 2013 at 22:46

3 Answers 3

4
var array_3 = array_1.concat(array_2);
Sign up to request clarification or add additional context in comments.

Comments

1

The way that you have your arrays set up is very strange. What you have are 2 arrays with 1 element in them each, and that element is an Object with 3 properties. The output that you listed is actually invalid javascript or JSON syntax. But, I can get you close to what you want, I think...

var array_1 = [{"a" : 1, "b" : 2, "c" : 3}];
var array_2 = [{"d" : 4, "e" : 5, "f" : 6}];
var array_3 = new Array();

function merge_objects(obj1,obj2){
    var obj3 = {};
    for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
    for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
    return obj3;
}

array_3[0] = merge_objects(array_1[0], array_2[0]);

Comments

0

What you're asking for is Array.prototype.concat which combines two arrays (or more) into a new array. All you need is:

var array_3 = array_1.concat(array_2);

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.