Skip to content

Instantly share code, notes, and snippets.

@AdamFrey
Created July 2, 2014 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AdamFrey/d14e58813a73de34943d to your computer and use it in GitHub Desktop.
Save AdamFrey/d14e58813a73de34943d to your computer and use it in GitHub Desktop.
Translate an object with Rails-style nested keys into an objected with nested keys. Depends on underscore.js
function nestParams(params) {
// Translates an object that has Rails style nested keys (key1[key2][key3]: value)
// into a nested object
var nested = {};
_.each(params, function(value, key) {
createNestedObject(nested, splitKey(key), value);
});
return nested;
}
function createNestedObject(base, keys, value) {
var lastKey = _.last(keys);
var keys = _.initial(keys);
_.each(keys, function(key) {
base = base[key] = base[key] || {};
});
base = base[lastKey] = value
return base;
}
function splitKey(string) {
return _.map(string.split("["), function(str) { return str.replace("]", "") });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment