Skip to content

Instantly share code, notes, and snippets.

@glenndevenish
Last active February 13, 2018 14:57
Show Gist options
  • Save glenndevenish/cc182fdf2f78e1387bf84f4d104851ff to your computer and use it in GitHub Desktop.
Save glenndevenish/cc182fdf2f78e1387bf84f4d104851ff to your computer and use it in GitHub Desktop.
Merge duplicates in JSON array.
/*
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