Skip to content

Instantly share code, notes, and snippets.

@UnquietCode
Last active July 25, 2017 15:05
Show Gist options
  • Select an option

  • Save UnquietCode/f6c32488a8094174e1f6 to your computer and use it in GitHub Desktop.

Select an option

Save UnquietCode/f6c32488a8094174e1f6 to your computer and use it in GitHub Desktop.
Merge two or more JSON objects in JavaScript (CoffeeScript).
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