jeudi 13 août 2015

Jascript - Comparing 2 Arrays of Object in the fastest and cleaner way

Assuming we have 2 arrays, A (source) and B (being saved).

var A = [ 
      { id: 1, value: 'Product Name 1' },
      { id: 2, value: 'Product Name 2' },
      { id: 3, value: 'Product Name 3' },
      { id: 4, value: 'Product Name 4' },
      { id: 5, value: 'Product Name 5' } 
]


var B = [ 
      { id: 1, value: 'Product Name 1' },
      { id: 2, value: 'Changed Name' },
      { value: 'New Product' }
]

Basically what i want to do is to compare both arrays, and check on array B, items are not present from array A which got deleted, the ones that had the 'value' property changed which got edited, and which ones are new which got added (basically without an id).

A logic goes like that (assuming that each A and B are one element from each array)

if A.id == B.id and A.value !== B.value then Edit

B.id doesnt exist then New

B.id is not on A then Deleted

I need to have a array of all the elements that got Added, Edited and Deleted

Expected Array would be

added = [ 
      { value: 'New Product'} 
]

edited = [ 
      { id: 2, value: 'Changed Name' }
]

deleted = [
      { id: 3, value: 'Product Name 3' },
      { id: 4, value: 'Product Name 4' },
      { id: 5, value: 'Product Name 5' } 
]



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire