Created
September 13, 2017 19:15
-
-
Save szanata/4ab0a8f53ae2e496d5d6a6d8ffd1890b to your computer and use it in GitHub Desktop.
Unflat js object
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 isObject(item) { | |
return (item && typeof item === 'object' && !Array.isArray(item)); | |
} | |
function mergeDeep(target, ...sources) { | |
if (!sources.length) return target; | |
const source = sources.shift(); | |
if (isObject(target) && isObject(source)) { | |
for (const key in source) { | |
if (isObject(source[key])) { | |
if (!target[key]) Object.assign(target, { [key]: {} }); | |
mergeDeep(target[key], source[key]); | |
} else { | |
Object.assign(target, { [key]: source[key] }); | |
} | |
} | |
} | |
return mergeDeep(target, ...sources); | |
} | |
function unflat(data) { | |
const result = []; | |
Object.keys(data).forEach( flatKey => { | |
const keys = flatKey.split('.'); | |
let unftn = { [keys[keys.length - 1]]: data[flatKey] }; | |
for (var i = keys.length - 1; i--;) { | |
unftn = { [keys[i]]: unftn } | |
} | |
result.push( unftn ) | |
}); | |
return mergeDeep( {}, ...result); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment