Created
May 25, 2012 12:44
-
-
Save bittersweetryan/2787854 to your computer and use it in GitHub Desktop.
Flatten a JavaScript Object into a Flat Object With Dot Notation Prop Names
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
function flatten(obj,prefix){ | |
var propName = (prefix) ? prefix + '.' : '', | |
ret = {}; | |
for(var attr in obj){ | |
if(_.isArray(obj[attr])){ | |
var len = obj[attr].length; | |
ret[attr] = obj[attr].join(','); | |
} | |
else if(typeof obj[attr] === 'object'){ | |
_.extend(ret,flatten(obj[attr], propName + attr)); | |
} | |
else{ | |
ret[propName + attr] = obj[attr]; | |
} | |
} | |
return ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: http://jsfiddle.net/bittersweetryan/5w5qQ/