/** * 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 }