Skip to content

Instantly share code, notes, and snippets.

@viebel
Last active December 15, 2020 06:13
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 viebel/f1c6ae2ca9d419c1735f2a85dd49bc9b to your computer and use it in GitHub Desktop.
Save viebel/f1c6ae2ca9d419c1735f2a85dd49bc9b to your computer and use it in GitHub Desktop.
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