Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- 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])
- }
Add Comment
Please, Sign In to add comment