Last active
March 23, 2017 15:57
-
-
Save eschwartz/2db194da7001143b4dea29698cc3c79a to your computer and use it in GitHub Desktop.
Flatten an 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
const _ = require('lodash'); | |
function flattenObj(obj, prefix) { | |
prefix || (prefix = ''); | |
return Object.keys(obj) | |
.reduce((flat, key) => ( | |
_.isObject(obj[key]) ? | |
// Recursively flatten objects | |
Object.assign(flat, flattenObj(obj[key], `${prefix}${key}.`)) : | |
// Assign flattened values to a prefixed key | |
Object.assign(flat, { | |
[prefix + key]: obj[key] | |
}) | |
), {}); | |
} | |
module.exports = flattenObj; |
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 * as _ from 'lodash'; | |
function flattenObj(obj:any, prefix:string = ''):any { | |
return Object.keys(obj) | |
.reduce((flat, key) => ( | |
_.isObject(obj[key]) ? | |
// Recursively flatten objects | |
Object.assign(flat, flattenObj(obj[key], `${prefix}${key}.`)) : | |
// Assign flattened values to a prefixed key | |
Object.assign(flat, { | |
[prefix + key]: obj[key] | |
}) | |
), {}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment