Search code examples
jsongoogle-apps-scriptnested-json

Unnest a nested JSON object


I have a nested JSON object below.

    var payload = {
      "name" : {
        "first" : "I am a",
        "last" : "Customer"
      },
      "product_info": {
        "name" : "Product 1",
        "category" : {
          "id" : "123456789",
          "name" : "C1",
          "sub_category" : {
            "id" : "321654987",
            "name" : "SC1"
          },
        }
      }};

    var param = JSON.stringify(payload);

How can I unnest the JSON object, so I can have the JSON object as below?

    var result = {
      "name.first" : "I am a",
      "name.last" : "Customer",
      "product_info.name" : "Product 1",
      "product_info.category.id" : "123456789",
      "product_info.category.name" : "C1",
      "product_info.category.sub_category.id" : "321654987",
      "product_info.category.sub_category.name" : "SC1"
    }

I was trying to use the Object.keys(param).length to check how many nested object there are, but if there isn't a nested object, it will return the length of the value.

Any suggestion would be appreciated.


Solution

  • Try the code below to flatten your JSON object at any nesting level:

    function myFunction(){
      var payload = {
          "name" : {
            "first" : "I am a",
            "last" : "Customer"
          },
          "product_info": {
            "name" : "Product 1",
            "category" : {
              "id" : "123456789",
              "name" : "C1",
              "sub_category" : {
                "id" : "321654987",
                "name" : "SC1"
              },
            }
          }};
          
      const flattenJSON = (payload = {}, res = {}, extraKey = '') => {
       for(key in payload){
          if(typeof payload[key] !== 'object'){
             res[extraKey + key] = payload[key];
          }else{
             flattenJSON(payload[key], res, `${extraKey}${key}.`);
          };
       };
       return res;
    };
    console.log(flattenJSON(payload));
    };
    

    Basically it's rebuilding your JSON object and assigning it to a new variable that is flattened object to the very first level. The process works by iterating through the object and if it's the last parameter on the object it will add a new key with value. The key is the appended keys of all keys that it goes through.

    This should return the unnested JSON objectenter image description here

    Reference link: https://www.tutorialspoint.com/flattening-a-json-object-in-javascript