Flattening a JSON object in JavaScript


Suppose, we have the following JSON object that may contain nesting upto any level −

const obj = {
   "one": 1,
   "two": {
      "three": 3
   },
   "four": {
      "five": 5,
      "six": {
         "seven": 7
      },
      "eight": 8
   },
   "nine": 9
};

We are required to write a JavaScript function that takes in one such nested JSON object and returns a new object that contains no nesting and maps the corresponding values to the keys using the dot notation.

Therefore, in case of the object above, the output should look something like this −

const output = {
   'one': 1,
   'two.three': 3,
   'four.five': 5,
   'four.six.seven': 7,
   'four.eight': 8,
   'nine': 9
};

Example

The code for this will be −

 Live Demo

const obj = {
   "one": 1,
   "two": {
      "three": 3
   },
   "four": {
      "five": 5,
      "six": {
         "seven": 7
      },
      "eight": 8
   },
   "nine": 9
};
const flattenJSON = (obj = {}, res = {}, extraKey = '') => {
   for(key in obj){
      if(typeof obj[key] !== 'object'){
         res[extraKey + key] = obj[key];
      }else{
         flattenJSON(obj[key], res, `${extraKey}${key}.`);
      };
   };
   return res;
};
console.log(flattenJSON(obj));

Output

And the output in the console will be −

{
   one: 1,
   'two.three': 3,
   'four.five': 5,
   'four.six.seven': 7,
   'four.eight': 8,
   nine: 9
}

Updated on: 22-Feb-2021

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements