Skip to content

Convert nested JSON to flat JSON JavaScript | Example code

  • by

You have to use multiple for loops to Convert nested JSON to flat JSON in JavaScript. Or can use a recursive function that iterates through the object and flattens it.

Convert nested JSON to flat JSON JavaScript

Simple example code will flat in 2-level JSON data.

<!DOCTYPE html>
<html>
<body>

  <script>
    var data=[
    {
      "a": "01AABCE2207R1Z5",
      "b": "Y",
      "c": [
      {
        "ca": "A",
        "cb": "AflJufPlFStqKBZ",
        "cc": "S008400"
      },
      {
        "cx": "A",
        "cy": "AflJufPlFStqKBZ",
        "cz": "S008400"
      }
      ]
    },

    {
      "a": "01AABCE2207R1Z5",
      "b": "Y",
      "c": [
      {
        "ca": "A",
        "cb": "AflJufPlFStqKBZ",
        "cc": "S008400"
      },
      {
        "cx": "A",
        "cy": "AflJufPlFStqKBZ",
        "cz": "S008400"
      }
      ]
    }
    ]
    
    var flatArray = [];
    var flatObject = {};

    for (var index = 0; index < data.length; index++) {
      for (var prop in data[index]) {

        var value = data[index][prop];

        if (Array.isArray(value)) {
          for (var i = 0; i < value.length; i++) {
            for (var inProp in value[i]) {
              flatObject[inProp] = value[i][inProp];
            }
          }
        }else{
          flatObject[prop] = value;
        }
      }
      flatArray.push(flatObject);
    }

    console.log(flatArray);
  </script>

</body>
</html> 

Output:

Convert nested JSON to flat JSON JavaScript

Here is an example recursive function:

function flattenJSON(obj) {
  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 + "[" + i + "]");
      }
      if (l == 0) {
        result[prop] = [];
      }
    } else {
      let isEmpty = true;
      for (let p in cur) {
        isEmpty = false;
        recurse(cur[p], prop ? prop + "." + p : p);
      }
      if (isEmpty && prop) {
        result[prop] = {};
      }
    }
  }
  recurse(obj, "");
  return result;
}
const nestedJSON = {
  a: 1,
  b: {
    c: 2,
    d: {
      e: 3,
      f: [4, 5, 6],
    },
  },
};

const flatJSON = flattenJSON(nestedJSON);

console.log(flatJSON);

Do comment if you have any doubts or suggestions on this JS flat JSON topic.

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

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

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

Continue reading