Reputation: 129
I have the following array
var x = [{"id":"757382348857","title":"title","handle":"linkhere","productimage":"url","ippid":true,"location_x":26,"location_y":18}]
And i am trying to add the following array into it
var y = [{"id":"75769d11","title":"newtitle"}]
What i am trying to do is to merge somehow the 2 arrays into 1. The final array should be
[{"id":"757382348857","title":"title","handle":"linkhere","productimage":"url","ippid":true,"location_x":26,"location_y":18},{"id":"75769d11","title":"newtitle"}]
Have tried
$.merge(x,y)
// x.join(y)
// x.push(y)
javascript
x.concat(y)
Any idea would be useful. Regards
Upvotes: 2
Views: 9026
Reputation: 1131
using jQuery
var x = [{"id":"757382348857","title":"title","handle":"linkhere","productimage":"url","ippid":true,"location_x":26,"location_y":18}]
var y = [{"id":"75769d11","title":"newtitle"}];
var mergedArray=$.merge(x,y);
var mergedString=JSON.stringify(mergedArray);
console.log(mergedString);
Upvotes: 3
Reputation: 21
var x = [{"id":"757382348857","title":"title","handle":"linkhere","productimage":"url","ippid":true,"location_x":26,"location_y":18}]
var y = [{"id":"75769d11","title":"newtitle"}]
var merged = x.concat(y);
Upvotes: 1
Reputation: 476
var newArray=x.concat(y)
will work.
With ES6
, You can also use spread operator ...
. Spread operator turns the items of an iterable(arrays, array like objects) into arguments of a function call or into elements of an Array.
So, to get new merged array you can do
var newArray=[...x, ...y]
If you want to merge the elements of x
and y
into x
, you can still use spread operator as x.push(...y)
Upvotes: 2
Reputation: 74738
Well, Array.concat()
method returns a new merged array. So, you have to store it in a variable to log it:
var x = [{"id":"757382348857","title":"title","handle":"linkhere","productimage":"url","ippid":true,"location_x":26,"location_y":18}]
var y = [{"id":"75769d11","title":"newtitle"}]
var merged = x.concat(y);
console.log(merged);
Upvotes: 3