需要最佳代码来检查以下json转换的几种条件

时间:2019-04-29 14:00:32

标签: javascript json

我提供的json实际上是我通过点击Rest Service得到的。 为简单起见,我直接在方法内部提供了该代码。 给出了一个带有textarea和accepr / Reject按钮的模态。

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.

我提供了我已经完成的代码,并且工作正常。

有人可以帮助我提供一些更好的最佳解决方案吗?

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>

0 个答案:

没有答案