Created
July 2, 2014 15:50
-
-
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
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 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