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
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);
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);
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)
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);
var mergedArray = [...x, ...y];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.