Skip to content

Flatten JSON JavaScript | Example code

Use for each or other logic to get Flatten JSON in JavaScript. Flattening a JSON object means converting it into a single-level object, where all nested objects and arrays are converted into key-value pairs. This process is useful when working with JSON data, as it allows you to easily access and manipulate the data.

Example Flatten JSON JavaScript

Simple example code using forEach.

<!DOCTYPE html>
<html>
<body>

  <script>
    var arr=[  
    { id: 1, name: "P1", groups: [ { id: 1.1, name: "G1.1" }, { id: 1.2, name:"G1.2" }]}, 
    { id: 2, name: "P2",  groups: [ { id: 2.1, name: "G2.1" }, { id: 2.2, name:"G2.2" }]}
    ];

    result = [];

    arr.forEach((o)=>{
      o.groups.forEach((group)=>{
        result.push({
          "id" : o.id,
          "name" : o.name,
          "group_id" : group.id,
          "group_name" : group.name
        });
      });
    });

    console.log(result);
  </script>

</body>
</html> 

Output:

Flatten JSON JavaScript

One-liner to flatten the nested object

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

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

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)
)

Source: stackoverflow.com

Or you can use a recursive function that iterates through the object and creates a new flattened object by concatenating the keys with a separator character. Here’s an example implementation:

function flattenObject(obj, separator = '_') {
  let result = {};
  function recurse(cur, prop) {
    if (Object(cur) !== cur) {
      result[prop] = cur;
    } else if (Array.isArray(cur)) {
      for (let i = 0, l = cur.length; i < l; i++)
        recurse(cur[i], prop + separator + i);
      if (l == 0) result[prop] = [];
    } else {
      let isEmpty = true;
      for (let p in cur) {
        isEmpty = false;
        recurse(cur[p], prop ? prop + separator + p : p);
      }
      if (isEmpty && prop) result[prop] = {};
    }
  }
  recurse(obj, '');
  return result;
}
let myObj = {
  "name": {
    "first": "John",
    "last": "Doe"
  },
  "address": {
    "city": "San Francisco",
    "state": "CA",
    "zip": 94111
  },
  "phoneNumbers": [
    {
      "type": "home",
      "number": "555-1234"
    },
    {
      "type": "work",
      "number": "555-5678"
    }
  ]
};

let flattenedObj = flattenObject(myObj);
console.log(flattenedObj);

Output:

{
  "name_first": "John",
  "name_last": "Doe",
  "address_city": "San Francisco",
  "address_state": "CA",
  "address_zip": 94111,
  "phoneNumbers_0_type": "home",
  "phoneNumbers_0_number": "555-1234",
  "phoneNumbers_1_type": "work",
  "phoneNumbers_1_number": "555-5678"
}

Comment if you have any doubts or suggestions on this JS flat topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

2 thoughts on “Flatten JSON JavaScript | Example code”

    1. 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));

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading