JavaScript Dynamic JSON - javascript

Need to dynamically select JSON key from the JSON Object itself.
var text =
'{"employees":[' + '{"firstName":"lastName", "lastName":"Doe" }]}';
var obj = JSON.parse(text);
var firstName = obj.employees[0].firstName;
var lName = obj.employees[0].firstName;
document.getElementById("demo").innerHTML =
firstName + " " + obj.employees[0].lName;
<div id="demo"></div>
Output Obtained: "lastName undefined".
Desired Output: "lastName Doe"

You need to change the code like follows
var text = '{"employees":[' +
'{"firstName":"lastName","lastName":"Doe" }]}';
obj = JSON.parse(text);
var firstName = obj.employees[0].firstName;
var lName = obj.employees[0].firstName;
document.getElementById("demo").innerHTML =
firstName + " " + obj.employees[0][lName];
Here is the working code:http://jsfiddle.net/NJMyD/5349/

Related

how to concatenate string with double quotes to generate JSON?

var skillTargetID = "1234";
var agentId = "2345";
var firstName = "Ganesh";
var lastName = "Putta";
var userName = "ganesh#gmail.com"
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/1234,agentId:2345,firstName:Ganesh,lastName:Putta,userName:ganesh#gmail.com"}
how to cancatenate string to get the exact result like first one.
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 = "ganesh#gmail.com"
console.log(createJSONString(skillTargetID, agentId, firstName, lastName, userName))

Writing text and a variable into HTML using Javascript

here is my code. I would like to print the variable 'fName' and the text prior into the div (with the ID 'feedback').
<script>
function myFunction() {
var first = document.getElementById("fName").value;
var last = document.getElementById("lName").value;
document.getElementById("feedback").innerHTML += "Hello" + fName;
}
</script>
Any help would be appreciated.
Just use the variables you have defined:
<script>
function myFunction() {
var first = document.getElementById("fName").value;
var last = document.getElementById("lName").value;
document.getElementById("feedback").innerHTML += "Hello " + first + " " + last;
}
</script>

getting undefined value:app script

Here, i am trying to send a mail to replyEmail specified below. But it is giving as undefined value. Why its happening even though i am giving correct email id in google form? Some times its coming correct. But for another time its giving as undefined value.
function sendEmail(e) {
/**
var email = e.values[1];
var item = e.values[2];
var cost = e.values[3];
*/
var serviceInformation = e.values[1],
language = e.values[2],
meetingType = e.values[3],
eventDate = e.values[4],
clientName = e.values[5],
detailedDirections = e.values[6],
onSitePOCName = e.values[7],
onSitePOCNumber = e.values[8],
department = e.values[9],
contactPhoneNumber = e.values[10],
approval = e.values[11]; //the one we need to modif,
requestorEmail = e.values[12],
managerEmail = e.values[13],
Language2 = e.values[14],
interpreterName = e.values[15],
interpreterAgency = e.values[16],
dateConformationSent = e.values[17],
specialNotes = e.values[18];
var url = 'https://script.google.com/a/macros/richmond.k12.va.us/s/AKfycbwuRr1boKTH0v1mprWmc7PE66_mQ_dmPE0lyWb7vkfiyW3pn31b/exec';
// might be that the & needs to be a ?
var approve = url + '?approval=true' + '?reply=' + requestorEmail;
var reject = url + '?approval=false' + '?reply=' + requestorEmail;
var html = "<HTML><body>"+
"<h2>please review</h2><br />"
+"<P>" + language +" " + serviceInformation
+"<p>" + meetingType+ " on "+ eventDate + " for " +clientName
+"<p>" + "Location: "+ department
+"<p>" + "requester: "+ requestorEmail+ " "+
"<p>"+
"Approve<br />"+
"<p>"+
"Reject<br />"+
"</HTML></body>";
var html = [
"<html>",
"<body>",
"<h2>please review</h2> <br/>",
"<p>" + language +" " + serviceInformation,
"<p>" + meetingType + " on " + eventDate + " for " + clientName,
"<p>Location: " + department,
"<p>Requester: " + requestorEmail,
"<p>Approve<br/>",
"<p>Reject<br />",
"</body>",
"</html>";
].join('');
MailApp.sendEmail(managerEmail, "Approval Request", "what no html?", {
htmlBody: html
});
}
function doGet(e) {
var app = UiApp.createApplication(),
aprovalResponce = (e.parameter.approval == 'true') ? 'Approved.' : 'Sorry, you need to reschedule',
msg = "Your manager said :" + aprovalResponce;
var replyEmail = e.parameter.reply; // !!!
Logger.log(replyEmail);
MailApp.sendEmail(replyEmail, "Approval Request", msg);
var helloWorldLabel = app.createLabel(msg);
app.add(helloWorldLabel);
return app;
}
Its because space is not accepted while parsing the data in google script.It should be encoded and then the data is to be send.It can be encoded using encodeURIcomponent().

JSON: Showing several values from a string

I'm new with JSON and Javascript. I'm trying to figure out how to print all of these and not just one of them?
<p id="demo"></p>
<script>
var text = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>
I'm sorry to duplicate #Davids answer, but a bit more to output all - add something like out variable to collect all the values and then output them:
var out='';
var text = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
var obj = JSON.parse(text);
for(var i=0; i < obj.employees.length; i++ ) {
out+=obj.employees[i].firstName + " " + obj.employees[i].lastName+'<br>';
}
document.getElementById("demo").innerHTML = out;
Try using a for-loop, you are just printing the values of index 1 in there maybe something like this should work
var text = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
obj = JSON.parse(text);
for (var i = 0; i < obj.employees.length; i++) {
document.getElementById("demo").innerHTML +=
obj.employees[i].firstName + " " + obj.employees[i].lastName + " ";
}
iterate over the object so you can add the values to the element :DD hope this helps
You can show it in a loop.
for (var i = 0; i < obj.employees.length; i++) {
document.getElementById("demo").innerHTML +=
obj.employees[i].firstName + " " + obj.employees[i].lastName;
}
NOTE: obj.employees.length = 3 (in this case)
If you ask me do it, i would do it like this. Code has been tested. Try it. I am using self executing function with strict check. Making using of javascript's prototype nature. I am assuming you have parsed JSON data and is available to use. Let me know if you need more explanation.
(function(){
'use strict';
var text = {
employees: [
{
firstName:'john',lastName:'Dae'
},
{
firstName:'Anna',lastName:'Smith'
},
{
firstName:'Peter',lastName:'Jones'
}
]
};
var Employee = function(data){
//private vars goes here.
this.employees = data.employees;
};
Employee.prototype.append = function(id_of_element){
for(var i = 0;i<this.employees.length;i++){
document.getElementById('demo').innerHTML += '<li>'+this.employees[i].firstName+ ' ' +this.employees[i].lastName+'</li>';
}
};
var emp = new Employee(text);
emp.append();
})();
var text = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
obj = JSON.parse(text);
obj.employees.forEach(function(employee) {
document.getElementById("demo").innerHTML += employee.firstName + " " + employee.lastName + "\n";
});
<pre id="demo"></pre>
For simplicity (but not necessarily performance) use ES5's array methods:
document.getElementById('demo').innerHTML =
obj.employees.map(function(employee) {
return employee.firstName + ' ' + employee.lastName;
}).join('<br>');
or in ES6 syntax:
document.getElementById('demo').innerHTML =
obj.employees.map(employee => employee.firstName + ' ' + employee.lastName)
.join('<br>');
Note how both of the above avoid the repeated dereferencing of obj.employees[i].
NB: this won't put a <br> after the final name, but if that matters you should be putting your list in a "block-styled" element which will implicitly move to the next line at the end for you.

Two Contents Added With Space

I'm trying to add contents from two DIVs and inject them into an input field. The following works except there is no space in between the values entered.
With the code below the values in the text field is: JohnDoeAccountant
I'm looking for an output in the text field of: John Doe Accountant.
How could I ensure there is a space in between the values of the outputs?
var output1 = document.getElementById("firstname").innerHTML;
var output2 = document.getElementById("lastname").innerHTML;
var output3 = document.getElementById("job").innerHTML;
document.getElementById("user-submitted-tags").value = output1 + output2 + output3;
Try
document.getElementById("user-submitted-tags").value = output1 + ' ' + output2 + ' ' + output3;
....value = [output1, output2, output3].join(" ");
Or cut out some repetition:
document.getElementById("user-submitted-tags").value =
["firstname","lastname","job"].map(function(id) {
return document.getElementById(id).innerHTML;
}).join(" ")
Or like this:
document.getElementById("user-submitted-tags").value =
["firstname","lastname","job"].reduce(function(s, id) {
return s + " " + document.getElementById(id).innerHTML;
}, "")

Categories