Skip to content

Instantly share code, notes, and snippets.

@fantactuka
Last active January 16, 2017 19:01
Show Gist options
  • Save fantactuka/4989737 to your computer and use it in GitHub Desktop.
Save fantactuka/4989737 to your computer and use it in GitHub Desktop.
var flattenObj = function (object, target, prefix) {
prefix = prefix || '';
return _(object).inject(function(result, value, key) {
if (_.isObject(value)) {
flattenObj(value, result, prefix + key + '.');
} else {
result[prefix + key] = value;
}
return result;
}, target || {});
};
console.log(flattenObj({attrs: {address: {state: 'NJ', city: 'NY'}, name: 'Bob'}, age: 32}));
/**
* Un-flattening objects
* { 'attr.address.street': 'Wall' } => {attr: {address: {street: 'Wall'}}}
*/
var unFlattenObj = function(object) {
return _(object).inject(function(result, value, keys) {
var current = result,
partitions = keys.split('.'),
limit = partitions.length - 1;
_(partitions).each(function(key, index) {
current = current[key] = (index == limit ? value : (current[key] || {}));
});
return result;
}, {});
};
console.log(unFlattenObj({'attrs.address.street': 'Wall', 'attrs.address.city': 'NY', 'attrs.address.state': 'NJ', 'attrs.name': 'Bob', 'age': 32}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment