Last active
February 13, 2018 14:57
-
-
Save glenndevenish/cc182fdf2f78e1387bf84f4d104851ff to your computer and use it in GitHub Desktop.
Merge duplicates in JSON array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
merge.js | |
Merge duplicates in JSON array. | |
*/ | |
old_array = [ | |
{ | |
"Some": "data", | |
"Here": "would", | |
"Be": "nice", | |
"Number": 123 | |
}, | |
{ | |
"Some": "data", | |
"That": "has", | |
"Duplicate": "keys", | |
"Number": 456 | |
}, | |
] | |
var new_obj = {} | |
for(sku in old_array) { | |
// Create key (this is so you can test duplicates based on multiple keys in original array) | |
key = old_array[sku].Key1 + " " + old_array[sku].Key2 | |
if(new_obj.hasOwnProperty(key)) { | |
// If it already exists, merge data together | |
// Now is an excellent time to log stuff | |
new_obj[key].Quantity += parseInt(old_array[sku].Quantity) | |
} else { | |
// Create a new object | |
new_obj[key] = { | |
// Duplicate object data | |
} | |
} | |
} | |
// Convert object to array | |
array = []; | |
for(sku in new_obj) { | |
array.push(new_obj[sku]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment