Guest User

Untitled

a guest
Jan 22nd, 2018
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. var jsonData = [{x:12, machine1: 7}, {x:15, machine2:7},{x:12, machine2: 8}];
  2.  
  3. var jsonData = [{x:12, machine1:7, machine2:8}, {x:15, machine2:7}]
  4.  
  5. // Loop through all objects in the array
  6. for (var i = 0; i < jsonData.length; i++) {
  7.  
  8. // Loop through all of the objects beyond i
  9. // Don't increment automatically; we will do this later
  10. for (var j = i+1; j < jsonData.length; ) {
  11.  
  12. // Check if our x values are a match
  13. if (jsonData[i].x == jsonData[j].x) {
  14.  
  15. // Loop through all of the keys in our matching object
  16. for (var key in jsonData[j]) {
  17.  
  18. // Ensure the key actually belongs to the object
  19. // This is to avoid any prototype inheritance problems
  20. if (jsonData[j].hasOwnProperty(key)) {
  21.  
  22. // Copy over the values to the first object
  23. // Note this will overwrite any values if the key already exists!
  24. jsonData[i][key] = jsonData[j][key];
  25. }
  26. }
  27.  
  28. // After copying the matching object, delete it from the array
  29. // By deleting this object, the "next" object in the array moves back one
  30. // Therefore it will be what j is prior to being incremented
  31. // This is why we don't automatically increment
  32. jsonData.splice(j, 1);
  33. } else {
  34. // If there's no match, increment to the next object to check
  35. j++;
  36. }
  37. }
  38. }
  39.  
  40. 12: [ {x=12, machine1=7}, {x=12, machine2=8} ],
  41. 15: [ {x=15, machine2=7} ]
  42.  
  43. var jsonData = [{x:12, machine1: 7}, {x:15, machine2:7},{x:12, machine2: 8}];
  44. var groupedByX = _.groupBy(jsonData, 'x');
  45. var result = [];
  46. _.forEach(groupedByX, function(value, key){
  47. var obj = {};
  48. for(var i=0; i<value.length; i++) {
  49. _.defaults(obj, value[i]);
  50. }
  51. result.push(obj);
  52. });
  53.  
  54. const mergeUnique = (list, $M = new Map(), id) => {
  55. list.map(e => $M.has(e[id]) ? $M.set(e.id, { ...e, ...$M.get(e.id) }) : $M.set(e.id, e));
  56. return Array.from($M.values());
  57. };
Add Comment
Please, Sign In to add comment