Last active
December 15, 2020 06:13
-
-
Save viebel/f1c6ae2ca9d419c1735f2a85dd49bc9b 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
function setVerbatim (obj, k, v) { | |
// In Lodash, a dot in a key is interpreted as a nesting object | |
// For instance, _.set({}, "a.b", 2) returns {"a": {"b": 2}} | |
// While setVerbatim({}, "a.b", 2) returns {"a.b": 2} | |
return _.merge(obj, {[k]: v}) | |
} | |
function flattenObject(obj, prefix = '') { | |
return _.reduce(obj, | |
function(acc, v, k) { | |
if (_.isObject(v) && !_.isEmpty(v)) { | |
return _.merge(acc, | |
flattenObject(v, | |
prefix + k + ".")) | |
} | |
return setVerbatim(acc, prefix + k, v); | |
}, | |
{}); | |
} | |
// without lodash | |
function flattenObject(obj, prefix = '') { | |
return Object.entries(obj).reduce( | |
function(acc, [k, v]) { | |
if (typeof(v) == "object") { | |
return Object.assign(acc, flattenObject(v, prefix + k + ".")); | |
} | |
acc[prefix + k] = v; | |
return acc; | |
}, | |
{}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment