Last active
January 16, 2017 19:01
-
-
Save fantactuka/4989737 to your computer and use it in GitHub Desktop.
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
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