var skillTargetID = "1234";
var agentId = "2345";
var firstName = "Ganesh";
var lastName = "Putta";
var userName = "[email protected]"
agentjson = {
"refURL": "/unifiedconfig/config/agent/" skillTargetID "," "agentId" ":" agentId "," "firstName" ":" firstName "," "lastName" ":" lastName "," "userName" ":" userName
};
console.log(agentjson);
I got a string like below
"refURL":"/unifiedconfig/config/agent/5113","agentId":"1312","firstName":"John","lastName":"Elway","userName":"jelway"
i need to concatenate above string using javascript with dynamic values, i tried, but in the result double quotes are not appending for every word.
agentjson={"refURL":"/unifiedconfig/config/agent/" skillTargetID "," "agentId" ":" agentId "," "firstName" ":" firstName "," "lastName" ":" lastName "," "userName" ":" userName};
this is result i got.
refURL: '/unifiedconfig/config/agent/5174,agentId:1082,firstName:Rick,lastName:Barrows,userName:[email protected]'
how to cancatenate string to get the exact result like first one.
CodePudding user response:
You need an object and then you need to stringify it
You can use template literals to embed variables in a string and the rest you can just write the variable name in the object
const createJSONString = (skillTargetID, agentId, firstName, lastName, userName) => {
const obj = {refURL : `/unifiedconfig/config/agent/${skillTargetID}`,
agentId, firstName, lastName, userName};
return JSON.stringify(obj);
}
var skillTargetID = "1234";
var agentId = "2345";
var firstName = "Ganesh";
var lastName = "Putta";
var userName = "[email protected]"
console.log(createJSONString(skillTargetID, agentId, firstName, lastName, userName))
CodePudding user response:
In JavaScript, you can concatenate the variables to get the desired output:
var skillTargetID = "1234";
var agentId = "2345";
var firstName = "Ganesh";
var lastName = "Putta";
var userName = "[email protected]"
var output = '{"refURL":"/unifiedconfig/config/agent/' skillTargetID '","agentId":"' agentId '","firstName":"' firstName '","lastName":"' lastName '","userName":"' userName '"}';
var json = JSON.parse(output);
console.log(json);