Created
December 20, 2017 12:27
-
-
Save r3b/24f27cd4c286e01d3a1ff2bec23f01d3 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
const flatten = object => { | |
return Object.assign( {}, ...function _flatten( objectBit, path = '' ) { //spread the result into our return object | |
return [].concat( //concat everything into one level | |
...Object.keys( objectBit ).map( //iterate over object | |
key => typeof objectBit[ key ] === 'object' ? //check if there is a nested object | |
_flatten( objectBit[ key ], `${ path }/${ key }` ) : //call itself if there is | |
( { [ `${ path }/${ key }` ]: objectBit[ key ] } ) //append object with it’s path as key | |
) | |
) | |
}( object ) ); | |
}; | |
const rehydrate = object => { | |
const recurse = (arr, obj, val) => { | |
return (!arr.length)? val : Object.assign(obj, {[arr.shift()]: recurse(arr, {}, val)}); | |
} | |
return Object.entries(object).map(entry => { | |
let [path, value] = entry; | |
return recurse(path.substring(1).split('/'), {}, value); | |
}); | |
}; | |
const isObject = (item) => (item && typeof item === 'object' && !Array.isArray(item) && item !== null); | |
const copy = (target, source) => { | |
let destination = Object.assign({}, target); | |
Object.keys(source).forEach(function (key) { | |
destination[key] = | |
(isObject(destination[key]) && isObject(source[key])) | |
? copy(destination[key], source[key]) | |
: source[key]; | |
}); | |
return destination; | |
} | |
const merge = (target, ...sources) => sources.reduce((p,c) => copy(p,c), target); | |
const realDeepObject = { | |
level1: { | |
level2: { | |
level3: { | |
more: 'stuff', //duplicate key | |
other: 'stuff', | |
level4: { | |
the: 'end', | |
}, | |
}, | |
}, | |
level2still: { | |
last: 'one', | |
}, | |
am: 'bored', | |
}, | |
more: 'stuff', //duplicate key | |
ipsum: { | |
lorem: 'latin', | |
}, | |
}; | |
const flat = flatten( realDeepObject ); | |
console.log( flat ); | |
console.log( copy(...rehydrate(flat)) ); | |
console.log( merge(...rehydrate(flat)) ); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment