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

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

Comments

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

Extend joins two objects/arrays into the first object.

2 Comments

The first parameter is used to make sure it does a deep recursion, and checks the values within the array.
If the attribute is the same in both, it'll be kept.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.