Skip to content

Instantly share code, notes, and snippets.

@zo0m
Created March 16, 2016 14:20
Show Gist options
  • Select an option

  • Save zo0m/92c5c4e765653cb98e49 to your computer and use it in GitHub Desktop.

Select an option

Save zo0m/92c5c4e765653cb98e49 to your computer and use it in GitHub Desktop.
Make object flatt paramObject.subParamObject.subSubSubParam - paramObject_subParamObject_subSubSubParam
convertFlatObject = (objectToFlat)->
flatObject = {}
convertValue = (flatObject, key, value)->
if value isnt null and value isnt undefined
if typeof value is "string" or typeof value is "number"
flatObject[key] = value
else if typeof value is "object"
flatSubObject = convertFlatObject value
for subObjectKey, subObjectValue of flatSubObject
flatObject["#{key}_#{subObjectKey}"] = subObjectValue
else if typeof value is "array"
arrayToFlat = value
for arrayToFlatValue, arrayToFlatIndex in arrayToFlat
convertValue flatObject, "#{key}_#{arrayToFlatIndex}", arrayToFlatValue
for key, value of objectToFlat
convertValue flatObject, key, value
flatObject
console.log convertFlatObject
currentParam : 0
sub1 : subParam : subSubParam : 1
sub2 : subParam : 2
sub3_arr : [
["subArr00", "subArr01"],
"arr1",
2
["subArr10", [ "subsubArr110"]]
]
###
currentParam: 0
sub1_subParam_subSubParam: 1
sub2_subParam: 2
sub3_arr_0_0: "subArr00"
sub3_arr_0_1: "subArr01"
sub3_arr_1: "arr1"
sub3_arr_2: 2
sub3_arr_3_0: "subArr10"
sub3_arr_3_1_0: "subsubArr110"
###
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment