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..?

1
  • does it work? did you test it?....
    – Naftali
    Aug 17, 2011 at 21:13

2 Answers 2

8

$.extend(arr1,arr2)

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

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

8
$.extend(true, arr1, arr2);

Extend joins two objects/arrays into the first object.

2
  • 1
    The first parameter is used to make sure it does a deep recursion, and checks the values within the array. Aug 17, 2011 at 21:15
  • If the attribute is the same in both, it'll be kept. Aug 18, 2011 at 6:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.