Last active
July 25, 2017 15:05
-
-
Save UnquietCode/f6c32488a8094174e1f6 to your computer and use it in GitHub Desktop.
Merge two or more JSON objects in JavaScript (CoffeeScript).
This file contains hidden or 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
| valueOrCopy = (obj) -> | |
| if not obj | |
| return undefined | |
| if (typeof obj).toLowerCase() is 'object' | |
| newObj = {} | |
| newObj[k] = v for own k,v of obj | |
| return newObj | |
| else | |
| return obj | |
| mergeObject = (current, next) -> | |
| for own k,v of next | |
| # add a property | |
| if not current[k] | |
| current[k] = valueOrCopy(v) | |
| # remove a property | |
| else if v == null | |
| current[k] = undefined | |
| # change a property | |
| else if current[k] != v | |
| # recursive copy | |
| if (typeof current[k]).toLowerCase() is 'object' and (typeof v).toLowerCase() is 'object' | |
| mergeObject(current[k], v) | |
| # plain copy | |
| else | |
| current[k] = valueOrCopy(v) | |
| module.exports = (objects...) -> | |
| # start a root | |
| root = {} | |
| # perform the merge | |
| for obj in objects | |
| mergeObject(root, obj) | |
| root.toJson = -> JSON.stringify(this, null, 2) | |
| return root |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment