JSON: Showing several values from a string - javascript

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.

Related

Google Docs Apps Script getBackgroundColor(Offset)

Let's say I have some sentences in Google Docs. Just one sentences as an example:
"My house is on fire"
I actually changed the background color so that every verb is red and every noun blue.
Now I want to make a list with all the verbs and another one with the nouns. Unfortunately getBackgroundColor() only seems to work with paragraphs and not with single words.
My idea was, to do something like this (I didn't yet have the time to think about how to do the loop, but that's not the point here anyway):
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var paragraphs = body.getParagraphs();
var colorVar = paragraphs[0].getText().match(/\w+/).getBackgroundColor(); // The regEx matches the first word. Next I want to get the background color.
Logger.log(colorVar);
}
The error message I get goes something like this:
"The function getBackgroundColor in the text object couldn't be found"
Thx for any help, or hints or comments!
You want to retrieve the text from a paragraph.
You want to retrieve each word and the background color of each word from the retrieved the text.
In this case, the color is the background color which is not getForegroundColor().
You want to achieve this using Google Apps Script.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
At first, the reason of your error is that getBackgroundColor() is the method of Class Text. In your script, getBackgroundColor() is used for the string value. By this, the error occurs.
In this answer, for achieving your goal, each character of the text retrieved from the paragraph is scanned, and each word and the background color of each word can be retrieved.
Sample script:
function myFunction() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var paragraphs = body.getParagraphs();
var textObj = paragraphs[0].editAsText();
var text = textObj.getText();
var res = [];
var temp = "";
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (c != " ") {
temp += c;
} else {
if (temp != "") res.push({text: temp, color: textObj.getBackgroundColor(i - 1)});
temp = "";
}
}
Logger.log(res) // result
}
When you run the script, the text of 1st paragraph is parsed. And you can see the result with res as an object.
In this sample script, the 1st paragraph is used as a test case. So if you want to retrieve the value from other paragraph, please modify the script.
References:
getBackgroundColor()
getBackgroundColor(offset)
editAsText()
If I misunderstood your question and this was not the direction you want, I apologize.
Here's a script your welcome to take a look at. It highlights text that a user selects...even individual letters. I did it several years ago just to learn more about how documents work.
function highLightCurrentSelection() {
var conclusionStyle = {};
conclusionStyle[DocumentApp.Attribute.BACKGROUND_COLOR]='#ffffff';
conclusionStyle[DocumentApp.Attribute.FOREGROUND_COLOR]='#000000';
conclusionStyle[DocumentApp.Attribute.FONT_FAMILY]='Calibri';
conclusionStyle[DocumentApp.Attribute.FONT_SIZE]=20;
conclusionStyle[DocumentApp.Attribute.BOLD]=false;
conclusionStyle[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT]=DocumentApp.HorizontalAlignment.LEFT;
conclusionStyle[DocumentApp.Attribute.VERTICAL_ALIGNMENT]=DocumentApp.VerticalAlignment.BOTTOM;
conclusionStyle[DocumentApp.Attribute.LINE_SPACING]=1.5;
conclusionStyle[DocumentApp.Attribute.HEIGHT]=2;
conclusionStyle[DocumentApp.Attribute.LEFT_TO_RIGHT]=true;
var br = '<br />';
var selection = DocumentApp.getActiveDocument().getSelection();
var s='';
if(selection) {
s+=br + '<strong>Elements in Current Selection</strong>';
var selectedElements = selection.getRangeElements();
for(var i=0;i<selectedElements.length;i++) {
var selElem = selectedElements[i];
var el = selElem.getElement();
var isPartial = selElem.isPartial();
if(isPartial) {
var selStart = selElem.getStartOffset();
var selEnd = selElem.getEndOffsetInclusive();
s+=br + 'isPartial:true selStart=' + selStart + ' selEnd=' + selEnd ;
var bgcolor = (el.asText().getBackgroundColor(selStart)=='#ffff00')?'#ffffff':'#ffff00';
el.asText().setBackgroundColor(selStart, selEnd, bgcolor)
}else {
var selStart = selElem.getStartOffset();
var selEnd = selElem.getEndOffsetInclusive();
s+=br + 'isPartial:false selStart=' + selStart + ' selEnd=' + selEnd ;
var bgcolor = (el.asText().getBackgroundColor()=='#ffff00')?'#ffffff':'#ffff00';
el.asText().setBackgroundColor(bgcolor);
}
var elType=el.getType();
s+=br + 'selectedElement[' + i + '].getType()= ' + elType;
if(elType==DocumentApp.ElementType.TEXT) {
var txt = selElem.getElement().asText().getText().slice(selStart,selEnd+1);
var elattrs = el.getAttributes();
if(elattrs)
{
s+=br + 'Type:<strong>TEXT</strong>';
s+=br + 'Text:<span style="color:#ff0000">' + txt + '</span>';
s+=br + 'Length: ' + txt.length;
s+=br + '<div id="sel' + Number(i) + '" style="display:none;">';
for(var key in elattrs)
{
s+= br + '<strong>' + key + '</strong>' + ' = ' + elattrs[key];
s+=br + '<input type="text" value="' + elattrs[key] + '" id="elattr' + key + Number(i) + '" />';
s+=br + '<input id="elattrbtn' + Number(i) + '" type="button" value="Save Changes" onClick="setSelectedElementAttribute(\'' + key + '\',' + i + ');" />'
}
s+='</div>Show/Hide';
}
}
if(elType==DocumentApp.ElementType.PARAGRAPH) {
var txt = selElem.getElement().asParagraph().getText();
var elattrs = el.getAttributes();
if(elattrs)
{
s+=br + '<strong>PARAGRAPH Attributes</strong>';
s+=br + 'Text:<span style="color:#ff0000">' + txt + '</span> Text Length= ' + txt.length;
for(var key in elattrs)
{
s+= br + key + ' = ' + elattrs[key];
}
}
}
s+='<hr width="100%"/>';
}
//var finalP=DocumentApp.getActiveDocument().getBody().appendParagraph('Total Number of Elements: ' + Number(selectedElements.length));
//finalP.setAttributes(conclusionStyle);
}else {
s+= br + 'No Elements found in current selection';
}
s+='<input type="button" value="Toggle HighLight" onclick="google.script.run.highLightCurrentSelection();"/>';
//s+='<input type="button" value="Exit" onClick="google.script.host.close();" />';
DocumentApp.getUi().showSidebar(HtmlService.createHtmlOutputFromFile('htmlToBody').append(s).setWidth(800).setHeight(450).setTitle('Selected Elements'));
}

Concat first item of array to first itiem of second array JavaScript

how can I concat more rationally first item of array to first of second array and so on? Basically automate console.log here is the code:
$("button#search").on("click", function(){
var inputVal = $("input#text").val();
$.getJSON("https://en.wikipedia.org/w/api.php?action=opensearch&search=" + inputVal +"&limit=5&namespace=0&format=json&callback=?", function(json) {
var itemName = $.each(json[1], function(i, val){
})
var itemDescription = $.each(json[2], function(i, val){
})
var itemLink = $.each(json[3], function(i, val){
})
console.log(itemName[0] + " " + itemDescription[0] + " " + itemLink[0]);
console.log(itemName[1] + " " + itemDescription[1] + " " + itemLink[1]);
console.log(itemName[2] + " " + itemDescription[2] + " " + itemLink[2]);
console.log(itemName[3] + " " + itemDescription[3] + " " + itemLink[3]);
console.log(itemName[4] + " " + itemDescription[4] + " " + itemLink[4]);
})//EOF getJSON
});//EOF button click
I believe this is what you are looking for:
for (var i = 0; i < itemName.length; i++) {
console.log(itemName[i] + " " + itemDescription[i] + " " + itemLink[i]);
}
If arrays have the same length, you could use map
var result = $.map(json[1], function(i, val){
var row = val + " " + json[2][i] + " " + json[3][i];
console.log(row);
return row;
}
Also you can use that result later, e.g.
console.log(result[0]);
Using es6 you can do the following:
(in your getJson callback):
function (json) {
const [value, optionsJ, descriptionsJ, linksJ] = json;
let whatIwant = [];
// choose one to loop through since you know they will all be the same length:
optionsJ.forEach(function (option, index) {
whatIwant.push({option: option, description: descriptionJ[index], link: linksJ[index]});
});
// use whatIwant here**
}
Your new whatIwant array will then contain objects for each set.

Parsing a JSON Array with JavaScript returning selected parts

I have a very simple snipplet for a json array and a javascript function that now returns a single argument:
<!DOCTYPE html>
<html>
<body>
<h2>JSON Array Test</h2>
<p id="outputid"></p>
<script>
var arrayinput = '{"collection":[' +
'{"firstAttr":"XXXA","secAttr":"13156161","lastAttr":"01" },' +
'{"firstAttr":"XXXB","secAttr":"11153325","lastAttr":"02" },' +
'{"firstAttr":"XXXC","secAttr":"14431513","lastAttr":"03" },' +
'{"firstAttr":"XXXC","secAttr":"161714","lastAttr":"01" },' +
'{"firstAttr":"XXXC","secAttr":"151415","lastAttr":"02" },' +
'{"firstAttr":"XXXC","secAttr":"114516","lastAttr":"02" },' +
'{"firstAttr":"XXXC","secAttr":"131417","lastAttr":"03" },' +
'{"firstAttr":"XXXC","secAttr":"1311865","lastAttr":"03" },' +
'{"firstAttr":"XXXC","secAttr":"1314153","lastAttr":"01" },' +
'{"firstAttr":"XXXC","secAttr":"13312163","lastAttr":"01" }]}';
obj = JSON.parse(arrayinput);
document.getElementById("outputid").innerHTML =
obj.collection[1].firstAttr + " " + obj.collection[1].secAttr;
</script>
</body>
</html>
Now the problem is that I don't want to return just one value but multiple ones. For example all entrys with lastAttr=01 should be returned.
Therefore I would need something along the line of:
for(var i in obj) {
if(lastAttr[i]="01") {
document.getElementById("outputid").innerHTML =
obj.collection[i].firstAttr + " " + obj.collection[i].secAttr;
} else {
}
}
Any idea on how to make this work?
If you want to perform a where you need to use Array.prototype.filter:
var filteredArr = arr.collection.filter(function(item) {
return item.lastAttr == "01";
});
And, finally, you can use Array.prototype.forEach to iterate results and perform some action:
var outputElement = document.getElementById("outputid");
filteredArr.forEach(function(item) {
// Check that I used insertAdyacentHtml to be sure that all items
// will be in the UI!
outputElement.insertAdjacentHTML("afterbegin", item.firstAttr + " " + item.secAttr);
});
Also, you can do it fluently:
var arr = {
collection: [{
firstAttr: "hello",
secAttr: "world",
lastAttr: "01"
}, {
firstAttr: "hello 2",
secAttr: "world 2",
lastAttr: "01"
}]
};
var outputElement = document.getElementById("outputid");
var filteredArr = arr.collection.filter(function(item) {
return item.lastAttr == "01";
}).forEach(function(item) {
outputElement.insertAdjacentHTML("afterbegin", item.firstAttr + " " + item.secAttr);
});
<div id="outputid"></div>
You need to iterate over the collection Array and append the new stuff. Right now you're iterating the outer object and overwriting the .innerHTML each time.
var out = document.getElementById("outputid");
for (var i = 0; i < obj.collection.length; i++) {
if(obj.collection[i].lastAttr=="01") {
out.insertAdjacentHTML("beforeend", obj.collection[i].firstAttr + " " + obj.collection[i].secAttr);
}
}
Note that I used == instead of = for the comparison, and .insertAdjacentHTML instead of .innerHTML.
if you want to replace html try this
(someCollection) array;
var r = new Array();
var j = -1;
r[++j] = '<ul class="list-group">';
for (var i in array) {
var d = array[i];
if (d.attribute== somevalue) {
r[++j] = '<li class="list-group-item">'
r[++j]=d.otherattribute;
r[++j] = '</li>';
}
}
r[++j] = '</ul>';
//for(var b in r) //alert to see the entire html code
//{ alert(r[b]);}
firstLoadOnPage = false;
var list = document.getElementById('SymptomSection');
list.innerHTML = r.join('');
this replaces the inside of element with classname "SymptomSection"

Generate arrays using dynamically generated forms

Basically, I'm using JavaScript to dynamically generate a form that allows from multiple entries within a single submission. Here's the code I'm using for that:
function addEvent()
{
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value - 1) + 2;
numi.value = num;
var divIdName = 'my' + num + 'Div';
var newdiv = document.createElement('div');
newdiv.setAttribute('id', divIdName);
newdiv.innerHTML = '<table id="style" style="background-color: #ffffff;"><tr><td colspan="2">Entry ' + num + '<hr \/><\/td><\/tr><tr><td><label>Item 1: <\/td><td><input name="item1_' + num + '" value="" type="text" id="item1" \/><\/label><\/td><\/tr><tr><td><label>Item 2: <\/td><td><input name="item2_' + num + '" type="text" id="item2" \/><\/label><\/td><\/tr><tr><td><label>Item 3: <\/td><td><input type="text" name="item3_' + num + '" id="item3" \/><\/label><\/td><\/tr><tr><td><label>Item 4: <\/td><td><select name="item4_' + num + '" id="item4"><option value="---">---<\/option><option value="opt_1">1<\/option><option value="opt_2">2<\/option><option value="opt_3">3<\/option><option value="opt_4">4<\/option><\/select><\/label><\/td><\/tr><\/table>';
ni.appendChild(newdiv);
}
This works just fine, generating the entries fields I need. Using console in-browser, I've even verified all the names are correct. The issue is that I need to then take the selections and generate output. I've tried several methods, but everything resulted in null values.
function generateVideo()
{
var entries = document.getElementById('theValue').value;
var item1 = {};
var item2 = {};
var item3 = {};
var item4 = {};
for(i = 1; i <= entries; i++)
{
item1[i - 1] = document.getElementById('item1_' + i);
item2[i - 1] = document.getElementById('item2_' + i);
item3[i - 1] = document.getElementById('item3_' + i);
item4[i - 1] = document.getElementById('item4_' + i);
}
var code = 'Copy code and paste it into Notepad<br \/>"Save as" filename.html<br \/><textarea name="" cols="45" rows="34">header template\n';
for(i = 0; i < entries; i++)
{
if(i != (entries - 1))
{
code = code + ' ["' + item1[i] + '", "' + item2[i] + '", "' + item3[i] + '", "' + item4[i] + '"],\n';
}
else
{
code = code + ' ["' + item1[i] + '", "' + item2[i] + '", "' + item3[i] + '", "' + item4[i] + '"]\n';
}
}
code = code + 'footer template<\/textarea>';
var result = document.getElementById("result");
result.innerHTML = code;
}
The output is as follows:
Copy code and paste it into Notepad<br />"Save as" CourseName_Unit_Chapter.html<br /><textarea name="" cols="45" rows="34">header template
["null", "null", "null", "null"]
footer template</textarea>
Now, certain fields can be null, that's fine (I'll do form validation after I get it working), but I'm getting null for every field regardless of what is entered.
I, originally, had the .value on the getElementByIds, but that only results in the script not running when the entries variable is greater than 0 (default), which is why I tried removing them.
function generateVideo()
{
var entries = document.getElementById('theValue').value;
var item1 = {};
var item2 = {};
var item3 = {};
var item4 = {};
for(i = 1; i <= entries; i++)
{
item1[i - 1] = document.getElementById('item1_' + i).value;
item2[i - 1] = document.getElementById('item2_' + i).value;
item3[i - 1] = document.getElementById('item3_' + i).value;
item4[i - 1] = document.getElementById('item4_' + i).value;
}
var code = 'Copy code and paste it into Notepad<br \/>"Save as" filename.html<br \/><textarea name="" cols="45" rows="34">header template\n';
for(i = 0; i < entries; i++)
{
if(i != (entries - 1))
{
code = code + ' ["' + item1[i] + '", "' + item2[i] + '", "' + item3[i] + '", "' + item4[i] + '"],\n';
}
else
{
code = code + ' ["' + item1[i] + '", "' + item2[i] + '", "' + item3[i] + '", "' + item4[i] + '"]\n';
}
}
code = code + 'footer template<\/textarea>';
var result = document.getElementById("result");
result.innerHTML = code;
}
I've also tried variations of multidimensional arrays, instead of four arrays, but got the same results.
The output, as indicated by the removal of the .value on the getElementByIds, is good. Basically, there is something wrong with my attempts to populate the arrays using the dynamically generated forms.
I suspect that the issue with the declaration of the element ID, but I'm not sure how else to declare it. This style of scripting is not my norm. ^^'
Anyone have any ideas on how to fix the for loop to generate the array?
replace all occurences of
itemN[i]
with
itemN[i].value
if that doesnt work add
console.log( itemN[i] )
and see what it outputs

What is the optimal way to load form data into a string and then to localStorage?

Is this the optimal way to load form data into a string and then to localStorage ?
I came up with this on my own, and I am not good in programming. It works, for what I need, but I am not sure if it's a bulletproof code?
<script>
var sg = document.getElementById("selectedGateway");
var sd = document.getElementById("selectedDestination");
var dm = document.getElementById("departureMonth");
var dd = document.getElementById("departureDay");
var dy = document.getElementById("departureYear");
var rm = document.getElementById("returnMonth");
var rd = document.getElementById("returnDay");
var ry = document.getElementById("returnYear");
var ad = document.getElementById("adults");
var ch = document.getElementById("option2");
$("#searchRequestForm").submit(function() {
var string = 'From: ' + sg.value + ' \nTo: ' + sd.value + ' \nDeparture: ' + dm.value + '/' + dd.value + '/' + dy.value + ' \nReturn: ' + rm.value + '/' + rd.value + '/' + ry.value + ' \nNumber of adults: ' + ad.value + ' \nNumber of children: ' + ch.value;
localStorage.setItem("string", string);
});
</script>
I would use something like the following so that I could deal with an object and its properties rather than a big string. Note that other than the jQuery selectors, this is pure JavaScript.
Demo: http://jsfiddle.net/grTWc/1/
var data = {
sg: $("#selectedGateway").val(),
sd: $("#selectedDestination").val()
// items here
};
localStorage.setItem("mykey", JSON.stringify(data));
To retrieve the data:
var data = JSON.parse(localStorage["mykey"]);
alert(data.sg);
See Also:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify
http://api.jquery.com/jQuery.parseJSON/
I prefer a table driven approach so there is no repeated code (DRY):
var ids = [
"selectedGateway", "From: ",
"selectedDestination", "\nTo :",
"departureMonth", "\nDeparture: ",
"departureDay", "/",
"departureYear", "/",
"returnMonth", " \nReturn: ",
"returnDay", "/",
"returnYear", "/",
"adults", " \nNumber of adults: ",
"option2", " \nNumber of children: "];
var submitStr = "";
for (var i = 0; i < ids.length; i+=2) {
submitStr += ids[i+1] + document.getElementById(ids[i]).value;
}
localStorage.setItem("string", submitStr);
You could define a function such as the one below to directly get the values by id so then it would be simpler when you build your string.
function form(id) {
return document.getElementById(id).value;
}

Categories