Here you go:

Object.assign({}, ...function _flatten(o) { return [].concat(...Object.keys(o).map(k => typeof o[k] === 'object' ? _flatten(o[k]) : ({[k]: o[k]})))}(yourObject))

Summary: recursively create an array of one-property objects, then combine them all with Object.assign.

This uses ES6 features including Object.assign or the spread operator, but it should be easy enough to rewrite not to require them.

For those who don't care about the one-line craziness and would prefer to be able to actually read it (depending on your definition of readability):

Object.assign(
  {}, 
  ...function _flatten(o) { 
    return [].concat(...Object.keys(o)
      .map(k => 
        typeof o[k] === 'object' ?
          _flatten(o[k]) : 
          ({[k]: o[k]})
      )
    );
  }(yourObject)
)
Answer from user663031 on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › flatten-javascript-objects-into-a-single-depth-object
Flatten JavaScript objects into a single-depth Object - GeeksforGeeks
October 14, 2025 - // Declare an object let ob = { Company: "GeeksforGeeks", Address: "Noida", contact: +91-999999999, mentor: { HTML: "GFG", CSS: "GFG", JavaScript: "GFG" } }; // Declare a flatten function that takes // object as parameter and returns the // flatten object const flattenObj = (ob) => { // The object which contains the // final result let result = {}; // loop through the object "ob" for (const i in ob) { // We check the type of the i using // typeof() function and recursively // call the function again if ((typeof ob[i]) === 'object' && !Array.isArray(ob[i])) { const temp = flattenObj(ob[i]); for (const j in temp) { // Store temp in result result[i + '.' + j] = temp[j]; } } // Else store ob[i] in result directly else { result[i] = ob[i]; } } return result; }; console.log(flattenObj(ob));
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › flat
Array.prototype.flat() - JavaScript | MDN
If the element is an array, it's flattened according to the depth parameter. ... const arrayLike = { length: 3, 0: [1, 2], // Array-like objects aren't flattened 1: { length: 2, 0: 3, 1: 4 }, 2: 5, 3: 3, // ignored by flat() since length is 3 }; console.log(Array.prototype.flat.call(arrayLike)); // [ 1, 2, { '0': 3, '1': 4, length: 2 }, 5 ]
🌐
GitHub
gist.github.com › penguinboy › 762197
Flatten javascript objects into a single-depth object · GitHub
Same thing as @mehrjoo, simply allows the possibility to have different formatter for the level 0 keys of your object · const flatten = (objectOrArray, prefix = '', formatter = (k) => (k)) => { const nestedFormatter = (k) => ('.' + k) const nestElement = (prev, value, key) => ( (value && typeof value === 'object') ?
🌐
30 Seconds of Code
30secondsofcode.org › home › javascript › object › flatten or unflatten object
Flatten or unflatten a JavaScript object - 30 seconds of code
January 3, 2024 - Otherwise, we add the appropriate prefixed key-value pair to the accumulator object. In the previous example, we used a delimiter of . to separate the keys, but this can be customized, using an additional argument. Finally, the last argument is used for the recursive calls and should always be omitted unless you want every key to have a prefix. const flattenObject = (obj, delimiter = '.', prefix = '') => Object.keys(obj).reduce((acc, k) => { const pre = prefix.length ?
🌐
Medium
medium.com › @anshumantsagar › flatten-a-nested-javascript-object-a14b2800f8bc
Flatten a nested JavaScript object | by Anshumantsagar | Medium
August 26, 2024 - The goal of this function is to take a nested JavaScript object and “flatten” it, meaning it will convert the nested structure into a single-level object where the keys reflect the original nesting using dot notation.
Find elsewhere
🌐
npm
npmjs.com › package › flatten-object
flatten-object - npm
April 25, 2015 - Flattens nested javascript objects into a single level.
      » npm install flatten-object
    
Published   Apr 25, 2015
Version   1.2.0
Author   Todd Kennedy
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-flatten-javascript-objects-into-a-single-depth-object
How to Flatten JavaScript objects into a single-depth Object?
September 14, 2022 - <!DOCTYPE html> <html> <head> <title>Simple Object Flattening</title> </head> <body> <div id="result1">Original Object: </div> <div id="result2">Flattened Object: </div> <script> var obj = { "a": 1, "b": 2, "c": { "d": 3, "e": 4 } }; var flattened = {}; for (var key in obj) { if (typeof obj[key] === "object" && obj[key] !== null) { for (var subKey in obj[key]) { flattened[subKey] = obj[key][subKey]; } } else { flattened[key] = obj[key]; } } document.getElementById("result1").innerHTML += JSON.stringify(obj); document.getElementById("result2").innerHTML += JSON.stringify(flattened); </script> </body> </html>
Top answer
1 of 2
1

You can try to do it with Array.reduce. It is better than original code because of 2 points:

  • We don't need to create an additional variable to show answer (newArr in my example is just for clear code, we can also not to use it and console.log the result directly)
  • In original code we use array.map method to save the "mutated" array in another variable and then destructing it so we have 2 loops. But we can do it with 1 loop, we just need to get each item in array and put it to another array without saving it anywhere

So I think that my example is less complex and faster.

P.S. I also think that we don't need pretty variable.

const content = [
    { role: 'row', id: 0, expressions: { formula: [ { id: 'L34', name: 'CommodityName' }, { id: 'L4', name: 'ItemId' } ] } },
    { role: 'column', id: 1, expressions: { formula: [ { id:'LC', name: 'Year' }, { id: 'LA', name: 'Month' } ] } },
    { role: 'body',  id: 2, expressions: { formula: [ { id:'L1B', name: 'Demand' } ] } }
];


const newArr = content.reduce((formulas, contentItem) => {
  contentItem.expressions.formula.forEach(formulaItem => formulas.push({
    contentId: contentItem.id,
    role: contentItem.role,
    ...formulaItem
  }));
  return formulas;
}, [])

console.log(newArr);

2 of 2
1

The original version is clear, but you can avoid the unnecessary mutation and assign to formulas in a single statement using a flat map.

const formulas = content.flatMap(o =>
  o.expressions.formula.map(
    (x) => ({ contentId: o.id, role: o.role, ...x })
  )
)

For older versions of JS that don't have the flatMap built in, there is a flat map idiom using Array.concat:

[].concat(...x.map(f))

where x.map(f) returns a possible nested array. This will flatten the array 1 level, which is typically all you need.

In your case, this becomes:

const formulas = [].concat(
  ...content.map(o => o.expressions.formula.map(
    (x) => ({ contentId: o.id, role: o.role, ...x })
  ))
)
🌐
LearnersBucket
learnersbucket.com › home › examples › javascript › deep flatten object in javascript – 1
Deep flatten object in Javascript - 1 - LearnersBucket
March 21, 2023 - Also we can use ES6 features to differentiate between object and array. const flatten = (obj, prefix) => { //store the result let output = {}; //iterate the object for(let k in obj){ let val = obj[k]; //new key const newKey = prefix ?
🌐
LabEx
labex.io › tutorials › flatten-javascript-object-with-recursion-28312
JavaScript Object Flattening | Recursion and Object Manipulation | LabEx
In this lab, we will explore a JavaScript function that flattens an object with the paths for keys. The function uses recursion and Object.keys() combined with Array.prototype.reduce() to convert every leaf node to a flattened path node.
🌐
DEV Community
dev.to › provish › flattening-a-javascript-object-2fo6
Flattening a Javascript Object - DEV Community
December 6, 2019 - Flattening deeply nested object can be easily achieved by using recursive technique.
🌐
Medium
saurabhnativeblog.medium.com › how-to-deep-flatten-object-in-javascript-16bc5a22382
How to deep flatten object in JavaScript | by Saurabh Mhatre | Medium
May 5, 2023 - To deep flatten an object in JavaScript and return the result as an object, we need to iterate through the object’s properties, create new properties with flattened values, and merge the resulting objects using the spread operator.
🌐
DEV Community
dev.to › chukwuma1976 › flatten-deeply-nested-objects-1c1p
Flatten Deeply Nested Objects - DEV Community
February 2, 2025 - In this method the typeof operator is used to identify nested objects. The array methods map() and some() are used. The former is familiar to most, but the latter requires explanation. The method some() takes a callback function returning a boolean value as an argument. If any (SOME) of the elements in the array meet the condition then the return value is true. There is also an every() method which is similar to some syntactically but returns true only if EVERY element meets the condition. function flatten(obj) { let flattenedObj = {}; //initial empty object to place new key value pairs //loop
🌐
W3Resource
w3resource.com › javascript-exercises › fundamental › javascript-fundamental-exercise-233.php
JavaScript fundamental (ES6 Syntax): Flatten an object with the paths for keys - w3resource
July 9, 2025 - Otherwise, it adds the appropriate prefixed key-value pair to the accumulator object. You should always omit the second argument, prefix, unless you want every key to have a prefix. ... // Define a function 'flattenObject' that flattens nested objects into a single-level object with dot-separated keys const flattenObject = (obj, prefix = '') => Object.keys(obj).reduce((acc, k) => { const pre = prefix.length ?
🌐
GitHub
gist.github.com › MatejBransky › 5a08028fec510d13194b80b0a2c5287e
Flatten javascript objects into a single-depth object with ES6 · GitHub
const realDeepObject = { level1: { level2: { level3: { more: 'stuff', //duplicate key other: 'stuff', level4: { the: 'end', }, }, }, level2still: { last: 'one', }, am: 'bored', }, more: 'stuff', //duplicate key ipsum: { lorem: 'latin', }, }; const flat = flatten( realDeepObject ); console.log( flat );
🌐
4Geeks
4geeks.com › how-to › javascript-array-flatten
How to flatten an array in JavaScript?
July 16, 2025 - Flattening an array in JavaScript is the process of converting a multi-dimensional array into a single one-dimensional array which means that we move all the elements within the multi-dimensional array into a single array, this process can be ...
🌐
freeCodeCamp
forum.freecodecamp.org › t › how-to-flatten-deeply-nested-array-of-objects-arrays-solved › 171690
How to flatten deeply nested Array of Objects & Arrays [SOLVED] - The freeCodeCamp Forum
January 30, 2018 - Hi guys, I thought this would be a pretty simple problem to solve, but I’m running in to some trouble flattening out an array of nested arrays and objects. I basically just want to flatten it out to one single array of values. Basically, I want to check if any of the array properties are ...
🌐
npm
npmjs.com › package › flatten-anything
flatten-anything - npm
February 19, 2025 - Flatten objects and replace nested props with 'prop.subprop'. A simple and small integration. Latest version: 4.0.2, last published: a year ago. Start using flatten-anything in your project by running `npm i flatten-anything`. There are 22 other projects in the npm registry using flatten-anything.
      » npm install flatten-anything
    
Published   Feb 19, 2025
Version   4.0.2