Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var jsonData = [{x:12, machine1: 7}, {x:15, machine2:7},{x:12, machine2: 8}];
- var jsonData = [{x:12, machine1:7, machine2:8}, {x:15, machine2:7}]
- // Loop through all objects in the array
- for (var i = 0; i < jsonData.length; i++) {
- // Loop through all of the objects beyond i
- // Don't increment automatically; we will do this later
- for (var j = i+1; j < jsonData.length; ) {
- // Check if our x values are a match
- if (jsonData[i].x == jsonData[j].x) {
- // Loop through all of the keys in our matching object
- for (var key in jsonData[j]) {
- // Ensure the key actually belongs to the object
- // This is to avoid any prototype inheritance problems
- if (jsonData[j].hasOwnProperty(key)) {
- // Copy over the values to the first object
- // Note this will overwrite any values if the key already exists!
- jsonData[i][key] = jsonData[j][key];
- }
- }
- // After copying the matching object, delete it from the array
- // By deleting this object, the "next" object in the array moves back one
- // Therefore it will be what j is prior to being incremented
- // This is why we don't automatically increment
- jsonData.splice(j, 1);
- } else {
- // If there's no match, increment to the next object to check
- j++;
- }
- }
- }
- 12: [ {x=12, machine1=7}, {x=12, machine2=8} ],
- 15: [ {x=15, machine2=7} ]
- var jsonData = [{x:12, machine1: 7}, {x:15, machine2:7},{x:12, machine2: 8}];
- var groupedByX = _.groupBy(jsonData, 'x');
- var result = [];
- _.forEach(groupedByX, function(value, key){
- var obj = {};
- for(var i=0; i<value.length; i++) {
- _.defaults(obj, value[i]);
- }
- result.push(obj);
- });
- const mergeUnique = (list, $M = new Map(), id) => {
- list.map(e => $M.has(e[id]) ? $M.set(e.id, { ...e, ...$M.get(e.id) }) : $M.set(e.id, e));
- return Array.from($M.values());
- };
Add Comment
Please, Sign In to add comment