I know looking this question might be simple, but I'm bit confused with the way of objects reacts in javascript. I tried to search as much as possible for a solution and couldn't find any.
Here, I wanted to send the below json request. (EXPECTED OUTPUT)
{
"request": {
"command": "transaction",
"commandData":{
"type": "sale",
"amount" : 0.00,
"tenderType" : "credit",
"referenceNumber": "",
"kiosk" :{
"machineName": "string",
"clinicId": "string"
}
}
}
}
{
"request": {
"command": "close",
"commanddata":{
}
}
}
{
"request": {
"command": "status",
"commanddata":{
}
}
}
For the above request, I have splitted as three json objects viz tempJson1, tempJson2 and tempJson3 and finally combine all the json objects and store in a variable called tempJson.
But, when I try to use Object.assign(), it is taking only the tempJson3 and not merging all three json objects.
Where am I missing? Any help?
var tempJson1 = {};
tempJson1.request = {};
tempJson1.request.command = "Transaction";
tempJson1.request.commandData = {};
tempJson1.request.commandData.type = "sale";
tempJson1.request.commandData.amount = document.getElementById("amount").value || "";
tempJson1.request.commandData.tendertype = document.getElementById("tendertype").value || "";
//tempJson.request.requireToken = document.querySelector('.consent').checked;
tempJson1.request.commandData.referenceNumber = "";
tempJson1.request.kiosk = {};
tempJson1.request.kiosk.machineName = document.getElementById("machineName").value || "";
tempJson1.request.kiosk.clinicId = document.getElementById("clinicId").value || "";
var tempJson2 ={};
tempJson2.request = {};
tempJson2.request.command = "close";
tempJson2.request.commandData = {};
var tempJson3 = {};
tempJson3.request = {};
tempJson3.request.command = "status";
tempJson3.request.commandData = {};
var tempJson = Object.assign({},tempJson1,tempJson2, tempJson3);
//var tempJson = tempJson1.concat(tempJson2);
console.log(tempJson);
console.log("tempJson = " + JSON.stringify(tempJson));
<div>
<input type="hidden" id="amount"/>
<input type="hidden" id="tendertype"/>
<input type="hidden" id="machineName"/>
<input type="hidden" id="clinicId"/>
</div>
PS: Need solution with pure javascript and no ES6.
requestan array?console.log(tempJson);to your question? It's still not clear (at least for me) what result do you want..