Search code examples
javascriptjsonoracle-jet

How convert a JSON format to another using Javascript?


Iam implementing datepicker using Oracle JET.The JET cookbook provides me sample Datapicker that has JSON file as below.

 "Holidays": {
  "*": {
     "1": {
        "14": {
           "className": "holiday"

        },
        "26": {
           "className": "holiday"

        }
     }
   }

And Json file I get from my rest services is as below

 [
 {
     "YEAR":"2017",
     "MONTH":"1",
     "DAY":[
     {
         "N_DAYS":"25",
         "className":"holiday"
     },
     {
         "N_DAYS":"25",
         "className":"holiday"
     }
 ]

      },
  ];

How I can convert JSON file I get from the rest services like above one provided in JET cookbook


Solution

  • myStuff = [
      {
         "YEAR":"2017",
         "MONTH":"1",
         "DAY":[
           {
               "N_DAYS":"14",
               "className":"holiday"
           },
           {
               "N_DAYS":"26",
               "className":"holiday"
           }
        ]
      },
    ];
    
    Holidays = {
      '*': { }
    }
    
    for (var i = 0; i < myStuff.length; i++) {
      var month = myStuff[i].MONTH;
      for (var j = 0; j < myStuff[i].DAY.length; j++) {
        if (typeof Holidays['*'][myStuff[i].MONTH] == 'undefined') {
          Holidays['*'][month] = {};
        }
        
        Holidays['*'][myStuff[i].MONTH][myStuff[i].DAY[j].N_DAYS] = {
          className: myStuff[i].DAY[j].className
        }
      }
    }
    
    Holidays = { Holidays: Holidays }
    console.log(Holidays);