1
\$\begingroup\$

A json i have provided which is actually i am getting by hitting a Rest Service. To keep it simple I have provided that directly inside the method. A modal with textarea and accepr/Reject button has been given.

Input Json:{
  "Reference No":"101",
  "Date Of Reporting":"2019/04/29",
  "Status":"",
  "Comments":"",
  "Organization Name":"ABC"
  }


Conditons:
1.Set the data entered in the textarea value to "Comments"  in json.
2.Transform the date format to 2019-04-29 and set it to "Date Of Reporting" by comaparing key name contains "date" .
3.set the status value as A or R based on the onclick button value passed to the method below.
4.Keep all other json data as same.

I have provided the code I have done and it is working fine.

Can anyone help me with some better optimal solutions?

function tansformJson(btn){

var jsonStr={
  "Reference No":"101",
  "Date Of Reporting":"2019/04/29",
  "Status":"",
  "Comments":"",
  "Organization Name":"ABC"
  }

var jsonData = {};
var y=document.getElementsByTagName('textarea');
for (var key in jsonStr) {
    if (jsonStr.hasOwnProperty(key)) {
          if(key=="Comments"){
				jsonData[key] = y[0].value; 
		   }
		   else if(key.toLowerCase().includes("date")){
				var date = new Date(jsonStr[key]); 
				var value =date.getFullYear()+ '-' +(date.getMonth() + 1) + '-' + date.getDate();
				jsonData[key]=value;
		  
		   }else if(key=='Status'&& btn=='approve'){
			   jsonData[key]='A';
			   
		   }else if(key=='Status'&&btn=='reject'){
			   jsonData[key]='R';
			   
		   }else 
			   jsonData[key]=jsonStr[key];
	  }
}

console.log(jsonData);
}
<div class="modal-dialog" role="document">
  <div class="modal-content">
    <div class="modal-header">
      <h5 class="modal-title">Comments</h5>
    </div>
    <div class="modal-body">
     <textarea rows="3" cols="50"></textarea>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" onclick="tansformJson('approve')">Accept</button>
        <button type="button" class="btn btn-primary" onclick="tansformJson('reject')">Reject</button>
        
      </div>
    </div>
  </div>

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.