6

I have two array objects :

 var arr1 =[{product_id: 2, name: 'stack'}, {product_id: 3, name: 'overflow'}];

 var  arr2 = [{product_id: 2, name: 'popo'},{product_id: 6, name: 'foo'}];

I do jquery like follows:

$.each(arr1 , function(){ 
      var productId = this.product_id;
       $.each(arr2 , function(productId){
        if(this.product_id != productId){
           arr2.push(this);
        }
       }); 
   });

at the end

arr2 must look like

     var  arr2 = [{product_id: 2, name: 'stack'}, {product_id: 3, name: 'overflow'},
             {product_id: 6, name: 'foo'}]

am i doing correct jquery coding..?

user882196
  • 1,691
  • 9
  • 24
  • 39

2 Answers2

8

$.extend(arr1,arr2)

This will copy (and overwrite duplicates) from arr2 to arr1.

Ref: http://api.jquery.com/jQuery.extend/

PhD
  • 11,202
  • 14
  • 64
  • 112
8
$.extend(true, arr1, arr2);

Extend joins two objects/arrays into the first object.

Justice Erolin
  • 2,869
  • 20
  • 19