Skip to content

Instantly share code, notes, and snippets.

@chrisross
Created July 11, 2020 13:47
Show Gist options
  • Save chrisross/e2215700b6a429d6447eed8a3be2495e to your computer and use it in GitHub Desktop.
Save chrisross/e2215700b6a429d6447eed8a3be2495e to your computer and use it in GitHub Desktop.
Simple object flattener.
/**
* Converts an object or array to an 1 dimensional object
* with dot delimited key paths as keys
*
* @param {(Object|Array)} oldObject
* @returns {Object}
*/
const flat = oldObject => {
// This scope is just to create the new object, to avoid mutating state
const newObj = {};
return flatten(oldObject);
/**
* Flatten the object
*
* @param {(Object|Array)} object
* @param {string[]} [keys=[]]
*/
function flatten(object, keys = []) {
// Can iterate over arrays or objects
for (let key in object) {
const value = object[key];
// Can iterate over arrays or objects
if (typeof value === 'object') {
// Optimistically assume `key` is a sane type like string
// You could do a skip instead:
// (typeof key !== 'string') continue
// Or, coerce to string (must handle null)
flatten(value, [...keys, key]);
} else {
// You could have an options argument to `flat` with delimiter
// And key transform function like the `flat` npm module
newObj[keys.concat([key]).join('.')] = value;
}
}
return newObj;
}
};
// Examples:
// const o = {
// a: {
// b: [
// {
// c: 1
// },
// {
// d: {
// e: 100
// }
// }
// ]
// }
// }
//
// flat(o);
// #=> { 'a.b.0.c': 1, 'a.b.1.d.e': 100 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment