Guest User

Untitled

a guest
Feb 25th, 2018
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.84 KB | None | 0 0
  1. /*
  2. merge.js
  3. Merge duplicates in JSON array.
  4. */
  5.  
  6. old_array = [
  7. {
  8. "Some": "data",
  9. "Here": "would",
  10. "Be": "nice",
  11. "Number": 123
  12. },
  13. {
  14. "Some": "data",
  15. "That": "has",
  16. "Duplicate": "keys",
  17. "Number": 456
  18. },
  19. ]
  20.  
  21. var new_obj = {}
  22. for(sku in old_array) {
  23. // Create key (this is so you can test duplicates based on multiple keys in original array)
  24. key = old_array[sku].Key1 + " " + old_array[sku].Key2
  25. if(new_obj.hasOwnProperty(key)) {
  26. // If it already exists, merge data together
  27. // Now is an excellent time to log stuff
  28. new_obj[key].Quantity += parseInt(old_array[sku].Quantity)
  29. } else {
  30. // Create a new object
  31. new_obj[key] = {
  32. // Duplicate object data
  33. }
  34. }
  35. }
  36.  
  37. // Convert object to array
  38. array = [];
  39. for(sku in new_obj) {
  40. array.push(new_obj[sku])
  41. }
Add Comment
Please, Sign In to add comment