How To Flatten Objects In Javascript – Quick Examples

Welcome to a quick tutorial on how to flatten objects in Javascript. Need to simplify a nested object in Javascript? Here’s some bad news… There are no native functions to flatten objects in Javascript.

We have to manually define our own function on how to restructure nested objects. Yep, it’s kind of a sticky situation, so let us walk through a few examples in this guide – Read on!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TABLE OF CONTENTS

Download & Notes Flatten Objects Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

FLATTEN OBJECTS

All right, let us now get into the examples of how to flatten objects in Javascript.

 

1) FLATTEN TO SINGLE LEVEL

1-flat-obj.html
// (A) FLATTEN OBJECT FUNCTION
// CREDITS: https://gist.github.com/penguinboy/762197
var flatten = function (o) {
  var tempA = {};
  for (let i in o) {
    if ((typeof o[i]) == 'object') {
      var tempB = flatten(o[i]);
      for (let j in tempB) { tempA[i + '.' + j] = tempB[j]; }
    } else { tempA[i] = o[i]; }
  }
  return tempA;
};

// (B) THE NESTED OBJECT
var oNest = {
  name : {
    first : "Jon",
    last : "Doe"
  },
  age : 123,
  colors : ["Red", "Green", "Blue"]
};
console.log(oNest);

// (C) FLATTEN OBJECT
/*
 * name.first : "Jon",
 * name.last : "Doe",
 * age : 123,
 * colors.0 : "Red",
 * colors.1 : "Green",
 * colors.2 : "Blue"
 */
var oFlat = flatten(oNest);
console.log(oFlat);

This is probably one of the better ways to flatten an object, by using a recursive flatten() function. It may seem complicated at first, but do a quick trace and it really isn’t that bad.

  1. var tempA = {} is a temporary object that we will use for the reduction process.
  2. Loop through each property of the object –  for (let i in o).
  3. If the property is an object or array, we send it into a recursive loop – if (typeof o[i]=="object") { var tempB = flatten(o[i]); }
  4. Then use for (let j of tempB) to “dig” into the nested properties, reduce them into tempA[i + "." + j] = tempB[j];
  5. Lastly, “flat values” are simply added to tempA[i] = o['i'];

 

 

2) FLATTEN TO ARRAY

2-flat-array.html
// (A) FLATTEN TO ARRAY
var flatten = function (o) {
  var temp = [];
  for (let i in o) {
    temp.push(i);
    if ((typeof o[i]) == 'object') {
      temp = temp.concat(flatten(o[i]));
    } else { temp.push(o[i]); }
  }
  return temp;
};

// (B) THE NESTED OBJECT
var oNest = {
  name : {
    first : "Jon",
    last : "Doe"
  },
  age : 123,
  colors : ["Red", "Green", "Blue"]
};
console.log(oNest);

// (C) FLATTEN OBJECT
// ["name", "first", "Jon", "last", "Doe", "age", 123, "colors", "0", "Red", "1", "Green", "2", "Blue"]
var oFlat = flatten(oNest);
console.log(oFlat);

Following up from the previous example, this is the same recursive loop but modified to extract all the keys and values into an array.

  • To extract the keys only, remove else { temp.push(o[i]); }.
  • To extract the values only, remove temp.push(i).

 

 

3) ES6 FLATTEN

3-flat-es6.html
// (A) ES6 FLATTEN
// https://github.com/30-seconds/30-seconds-of-code/blob/master/snippets/flattenObject.md
const flatten = (obj, prefix = '') =>
  Object.keys(obj).reduce((acc, k) => {
  const pre = prefix.length ? prefix + '.' : '';
  if (typeof obj[k] === 'object') Object.assign(acc, flatten(obj[k], pre + k));
  else acc[pre + k] = obj[k];
  return acc;
}, {});

// (B) FLATTEN OBJECT
var oFlat = flatten({
  name : {
    first : "Jon",
    last : "Doe"
  },
  age : 123,
  colors : ["Red", "Green", "Blue"]
});
console.log(oFlat);

For you guys who are looking for an “updated way” of reducing objects… Here’s how it can be done in ES6.

 

USEFUL BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

INFOGRAPHIC CHEAT SHEET

How To Flatten Objects In Javascript (click to enlarge)

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *