2

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

3
  • 3
    Use x.push(y[0]) Commented Dec 17, 2018 at 14:04
  • 3
    x.concat(y) worked for me. What is the issue? Commented Dec 17, 2018 at 14:06
  • These arrays are strings , so i think that is why i can't concat them or push, as it seems it gives error. Think i need to transform from string into array ? Commented Dec 17, 2018 at 14:08

5 Answers 5

3

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

1 Comment

using jQuery without referencing, assuming everybody uses jQ?
2

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)

Comments

1
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);

Comments

0
var mergedArray = [...x, ...y];

2 Comments

I will upvote, if you elaborate your answer with helpful links and demo. This would not help OP to understand what is spread syntax
please explain your answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.