Last active
April 19, 2020 08:28
-
-
Save riffrain/040c8307fd3412f5f7202e75ea408770 to your computer and use it in GitHub Desktop.
object flatten and expand
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
import _ from 'lodash'; | |
const numberRE = /^(?:0|[1-9][0-9]*)$/; | |
const flatten = (originalData) => { | |
const result = {}; | |
const stack = []; | |
let paths = []; | |
let data = JSON.parse(JSON.stringify(originalData)); | |
while(true) { | |
data = { ...data }; | |
const key = Object.keys(data).shift(); | |
if (key) { | |
const element = data[key]; | |
delete data[key]; | |
if (element !== null && typeof element === 'object' && Object.keys(element).length) { | |
if (data) { | |
stack.push([data, [...paths]]); | |
} | |
data = element; | |
if (numberRE.test(key)) { | |
if (paths.length && paths[paths.length - 1] === '.') { | |
paths.pop(); | |
} | |
paths.push(`[${key}]`); | |
} else { | |
paths.push(key); | |
} | |
paths.push('.'); | |
} else { | |
result[`${paths.join('')}${key}`] = element; | |
} | |
} | |
if (!Object.keys(data).length) { | |
if (stack.length) { | |
[data, paths] = stack.shift(); | |
} else { | |
break; | |
} | |
} | |
} | |
return result; | |
} | |
const expand = (data) => { | |
const keys = []; | |
const values = []; | |
const dataKeys = Object.keys(data); | |
let key = dataKeys.shift(); | |
while(key) { | |
keys.push(`result.${key}`); | |
values.push(data[key]); | |
key = dataKeys.shift(); | |
} | |
const { result } = _.zipObjectDeep(keys, values); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment