Permalink
Browse files

initial flatten and unflatten functions

  • Loading branch information...
1 parent ca0bf4e commit dc153fdaa1b9488b293b3ecd9a8e05b02c938950 @kolektiv committed Sep 9, 2012
Showing with 55 additions and 1 deletion.
  1. +1 −0 README.md
  2. +51 −0 lib/underscore-object-tools.js
  3. +3 −1 package.json
View
@@ -0,0 +1 @@
+# underscore-object-tools
@@ -0,0 +1,51 @@
+var _ = require('underscore');
+
+function flatten (obj, target, prefix) {
+ target = target || {};
+ prefix = prefix || '';
+
+ _.each(obj, function (val, key) {
+ var pre = prefix === ''
+ ? key
+ : prefix + '.' + key;
+
+ if (!_.isObject(val)) {
+ target[pre] = val;
+ } else {
+ flatten(val, target, pre);
+ }
+ });
+
+ return target;
+};
+
+function unflatten (obj) {
+ var target = {};
+ var current = target;
+
+ _.each(obj, function (val, key) {
+ var parts = key.split('.');
+
+ while (parts.length > 1) {
+ var part = parts.shift();
+
+ if (!current[part]) {
+ current[part] = {};
+ }
+
+ current = current[part];
+ }
+
+ current[parts.shift()] = isNaN(val)
+ ? val
+ : +val;
+ current = target;
+ });
+
+ return target;
+};
+
+module.exports = {
+ flatten: flatten,
+ unflatten: unflatten
+};
View
@@ -18,7 +18,9 @@
"mixin",
"object"
],
- "dependencies": {},
+ "dependencies": {
+ "underscore": "1.3.x"
+ },
"devDependencies": {},
"optionalDependencies": {},
"license": "MIT"

0 comments on commit dc153fd

Please sign in to comment.