Skip to content

Instantly share code, notes, and snippets.

@bittersweetryan
Created May 25, 2012 12:44
Show Gist options
  • Save bittersweetryan/2787854 to your computer and use it in GitHub Desktop.
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
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;
}
@bittersweetryan
Copy link
Author

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