我提供的一个 json 实际上是我通过点击休息服务获得的。为了简单起见,我直接在方法中提供了它。已给出带有 textarea 和接受/拒绝按钮的模式。
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>