Skip to content

Instantly share code, notes, and snippets.

@alaindet
Last active January 25, 2021 17:31
Show Gist options
  • Save alaindet/a0c79ef833a6d6e231d39fcf024ccf24 to your computer and use it in GitHub Desktop.
Save alaindet/a0c79ef833a6d6e231d39fcf024ccf24 to your computer and use it in GitHub Desktop.
const isNumericString = (digits) => {
if (typeof digits !== 'string') {
return false;
}
return digits.match(/^\d+$/);
};
const deflatten = (flat, separator = '.') => {
const tree = {};
for (const key in flat) {
const value = flat[key];
const subKeys = key.split(separator);
let nested = tree;
for (let i = 0, len = subKeys.length; i < len; i++) {
const subKey = subKeys[i];
const nextSubKey = subKeys[i + 1];
const existing = nested[subKey];
// Initialize next nesting level
if (!existing) {
nested[subKey] = isNumericString(nextSubKey) ? [] : {};
}
// Store value
if (i === len - 1) {
nested[subKey] = value
}
// Go deeper
else {
nested = nested[subKey];
}
}
}
return tree;
};
const flat = {
'foo': 42,
'bar.baz.qez.0.name': 'alice',
'bar.baz.qez.1.name': 'bob',
'bar.baz.qez.2.name': 'charlie',
};
console.log(
JSON.stringify(deflatten(flat)),
);
// Result
// {"foo":42,"bar":{"baz":{"qez":[{"name":"alice"},{"name":"bob"},{"name":"charlie"}]}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment