Created
November 9, 2011 05:32
-
-
Save bamnet/1350511 to your computer and use it in GitHub Desktop.
Merge objects with combined keys
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
// Each table is an array [] of objects. | |
// Object MUST have all keys. | |
// Objects with matching keys will be merged into one object. | |
function merge(table1, table2){ | |
keys = ['key', 'note']; | |
var merged = table1; | |
for(i in merged){ | |
var obj1 = merged[i]; | |
for(j in table2){ | |
var obj2 = table2[j]; | |
var match = true; | |
for(k in keys){ | |
key = keys[k]; | |
match *= (obj1[key] == obj2[key]) | |
} | |
if(match){ | |
for(key in obj2){ | |
if(keys.indexOf(key) == -1){ | |
obj1[key] = obj2[key]; | |
} | |
} | |
delete table2[j]; | |
merged[i] = obj1; | |
} | |
} | |
} | |
for(i in table2){ | |
merged.push(table2[i]); | |
} | |
return merged; | |
} | |
// Note: This is O(N^2) in the worst case, you probably shouldn't use this for very large arrays. | |
// A better approach would be to use the keys to generate a hash and mock a Map<hash, object> for merging, | |
// but when hashing keys is hard this will work via brute force. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment