Skip to content

Instantly share code, notes, and snippets.

@eschwartz
Last active March 23, 2017 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eschwartz/2db194da7001143b4dea29698cc3c79a to your computer and use it in GitHub Desktop.
Save eschwartz/2db194da7001143b4dea29698cc3c79a to your computer and use it in GitHub Desktop.
Flatten an object
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;
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