Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This is used to convert a flat file into a nested object structure, give the flat file is in proper dot notation.
/*
*
* @function constructObject
* @param {file} file in dot notation ('a.b.c':'Hey', 'd.e.g': 'you')
* @return {Object} - a nested object.
* @example
* const object = constructObject(file)
* Returns the following:
* a: {
* b: {
* c: 'hey'
* }
* }
* d: {
* e: {
* g: 'you'
* }
* }
*/
import _ from 'lodash'
// Get the nested object/key without the value
const getKey = (arr) => {
const nestedObject = {}
arr.reduce((o, s, index) => { if (index+1 < arr.length) { return o[s] = {} } }, nestedObject) //eslint-disable-line
return nestedObject
}
// Get the full object here
const getNested = (arr, val) => {
const nestedObject = {}
arr.reduce((o, s, index) => { if (index+1 === arr.length) { return o[s] = val } else { return o[s] = {} } }, nestedObject) //eslint-disable-line
return nestedObject
}
const constructObject = (file) => {
let final = {}
const parsed = JSON.parse(file)
Object.keys(parsed).forEach((key) => {
const keysArr = key.split('.')
if (keysArr.length > 1) {
final = _.merge(final, getKey(keysArr), getNested(keysArr, parsed[key]))
} else { final[keysArr[0]] = parsed[key] }
})
return final
}
export default constructObject
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.