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.

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

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

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.