Skip to content

Instantly share code, notes, and snippets.

@defkode
Created July 19, 2013 12:58
Show Gist options
  • Save defkode/6038935 to your computer and use it in GitHub Desktop.
Save defkode/6038935 to your computer and use it in GitHub Desktop.
flatten JSON
window.flattenJSON = (obj) ->
flattened = {}
join = (path, key) ->
(if path is "" then "" else path + "_") + key
flattenArray = (arr, path) ->
flattenElement(arr, path, i) for i in [0...arr.length]
flattenObject = (obj, path) ->
flattenElement(obj, path, key) for own key of obj
flattenElement = (obj, path, key) ->
if (toString.call(obj[key]) is '[object Array]')
flattenArray(obj[key], join(path, key))
else if (typeof obj[key] is "object")
flattenObject(obj[key], join(path, key))
else
flattened[join(path, key)] = obj[key]
flattenObject(obj, "")
flattened
@defkode
Copy link
Author

defkode commented Jan 26, 2018

# window.flattenJSON = (obj) ->
#   flattened = {}

#   join = (path, key) ->
#     (if path is "" then "" else path + "_") + key

#   flattenArray = (arr, path) ->
#     flattenElement(arr, path, i) for i in [0...arr.length]

#   flattenObject = (obj, path) ->
#     flattenElement(obj, path, key) for own key of obj

#   flattenElement = (obj, path, key) ->
#     if (toString.call(obj[key]) is '[object Array]')
#       flattenArray(obj[key], join(path, key))
#     else if (typeof obj[key] is "object")
#       flattenObject(obj[key], join(path, key))
#     else
#       flattened[join(path, key)] = obj[key]

#   flattenObject(obj, "")
#   flattened

window.flattenJSON = (obj) ->
  flattened = {}

  join = (path, key) ->
    (if path is "" then "" else path + "_") + key

  flattenObject = (obj, path) ->
    flattenElement(obj, path, key) for own key of obj

  flattenElement = (obj, path, key) ->
    if (Object.prototype.toString.call(obj[key]) is '[object Object]')
      flattenObject(obj[key], join(path, key))
    else
      flattened[join(path, key)] = obj[key]

  flattenObject(obj, "")
  flattened

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment