createHtmlOutputFromFile then append variable as an object from the function - javascript

I want to pass all values from Google Sheets to HTML (Google web app) by using Google-Apps-Script doGet() and append in the script to keep as global variable. Faster than html load first then use google.run.script... in my opinion
So getting an object key as a sheet_name and key values as 2D_array data
function getSheetData() {
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets()
var object = {}
for (var i = 0; i < sheets.length; i++) {
object[sheets[i].getName()] = sheets[i].getDataRange().getValues().filter(r => r[0] !== '')
}
return object
}
in function doGet() I'm using append to add the script to the HTML
function doGet() {
var html = HtmlService.createHtmlOutputFromFile('Main')
html.append('<script> var userData = ' + getSheetData() + ' </script>')
return html
}
Still getting <script> var userData = [object Object] </script>
it should be something like <script> var userData = {key1:[2D Array],key2:[2D Array]} </script>
I also tried with string and it works fine. But can we possibly do as an object?
Thank you in advance

html.append(' var userData = ' + getSheetData() + ' ')
When appending html, the script is appending a string. The object returned by getSheetData() is coerced to a string implicitly, when using the + operator. The coercion doesn't produce a full array as string but just as [object Object].
To bypass this, you may use JSON.stringify() server side:
html.append('<script> var userData = ' + JSON.stringify(getSheetData()) + ' </script>')

Related

Oracle Apex changing a String of a object

So I want to get the Object which is essentialy a string. The issue is I cant transfer it into the string format since the resulting string is just anything but the thing I want. Bringing the object into a json doesnt bring a proper string either so my only way of achieving that is the concat method.
I have a Popup-Love which returns the string as follows foo, foo1 ,foo2 while I need it as
'foo1','foo2',...,'foo999' .
My method manages to do that for the first element while all the other elements remove the apostrophe resulting in something like 'foo,foo1,foo2'. How do i fix that?
var i = 0;
if(i == 0){
var t ="'";
var t = t.concat(apex.item("P29_STANDORT").getValue());
var t = t.concat("'");
apex.item("P29_TEST").setValue(t);
i = i +1;
} else {
var t = t.concat("'");
var t = t.concat(apex.item("P29_STANDORT").getValue());
var t = t.concat("'");
apex.item("P29_TEST").setValue(t);
}
You can "overwrite" the native toString() function of the Object and replace it with a function that does what you want. Something like below
function MyObj(){
this.creationTime = new Date().toLocaleString();
}
MyObj.prototype.toString = function something(){
return 'I was created on ' + this.creationTime;
}
var myObj = new MyObj();
console.log('String version of my custom object: ' + myObj);

JavaScript get Objects property

Hello guys I've web page which have a lot of scripts, I need to get one by it's name. for e.g 'data'. I need to convert data from this script to one string.
Script is the following:
<script>data = [{'Id': '12344567', 'name': 'TestName','Amount': '1066.00', 'NumberTax': '34.00','tranasactionNumber':'139', 'otherInfo': [{'sku': 'ET|Adult','name': 'Test','category': 'Normal','price': '1032.0', 'quantity':'3'}]}];</script>
This data has array with some elements and another array inside.
Using my script I can only get info and create string with String elements from my data, but how can I get elements from inner array?
var json = '[{';
for (var i in data[0]) {
console.log('type of data[0][i] = ' + typeof data[0][i]);
if (typeof data[0][i] === 'string') {
json = json + '\'' + i + '\'' + ': ' + '\'' + data[0][i] + '\', ';
console.log(i);
console.log(data[0][i])
} else {
//Get infro from inner array
}
}
json = json + '}]';
console.log(json);
Try JSON.stringify(data) to convert object to string instead of your function.
To access the object inside the array you can use the following code:
var obj = data[0]['otherInfo'][0];
You can then use the same code you have above to loop over it and append its elements. If I understand correctly that if what you wish to do.

Javascript string variable to link

I'm making a chrome extension and I want to convert my javascript string variable into a clickable link. This is what my code does right now,
var regex = /[\w]+[\/]+[\w]+#(?:\d*\.)?\d+/g;
This finds a format on a page e.g. stack/overflow#12453. I convert the regex into a string with this function
function objectToString(object) {
var stringify = "";
for (var property in object) {
stringify += object[property] + '<br>';
}
return stringify;
}
What i want to do is to make that string into a clickable link. So if there are 5 links on a page, each of the strings returned would be a clickable link to a href. Is this possible? I would gladly appreciate any help.
Try this :
var obj = new Object();
obj.link1 = "www.google.com";
obj.link2 = "www.msn.com";
$().ready(function () {
$.each(objectToString(obj).split(','), function (i) {
$("ul").append("<li>" + objectToString(obj).split(',')[i] + "</li>");
});
});
function objectToString(object) {
var stringify = "";
for (var property in object) {
stringify += object[property] + ",";
}
stringify = stringify.slice(0, stringify.length - 1);
return stringify;
}
Jsfiddle : http://jsfiddle.net/u4hghL9c/

How do I extract JSON string using a JavaScript variable?

I am currently trying to retrieve the corresponding dial_code by using the name which I am obtaining as a variable.
The application uses a map of the world. When the user hovers over a particular country, that country is obtained using 'getRegionName'. This is then used to alter the variable name. How can I use the variable name to retrieve the dial_code that it relates to?
JSON
var dialCodes = [
{"name":"China","dial_code":"+86","code":"CN"},
{"name":"Afghanistan","dial_code":"+93","code":"AF"}
];
The following code runs on mouse hover of a country
var countryName = map.getRegionName(code);
label.html(name + ' (' + code.toString() + ')<br>' + dialCodes[0][countryName].dial_code);
This code doesn't work correctly. The dialCodes[0][countryName].dial_code is the part that is causing the error, but I'm not sure how to correctly refer to the corresponding key/value pair
If you have to support old browsers:
Loop over the entries in the array and compare to the given name:
var dialCode;
for(var i = 0; i < dialCodes.length; i++) {
if(dialCodes[i].name === countryName) {
dialCode = dialCodes[i].dial_code;
break;
}
}
label.html(countryName + ' (' + dialCode + ')');
If you browser support Array.prototype.filter:
dialCodes.filter(function(e) { return e.name === 'China' })[0].dial_code
If you have control over it, I recommend making your object more like a dictionary, for example if you are always looking up by the code (CN or AF) you could avoid looping if you did this:
var dialCodes = {
CN: { "name":"China","dial_code":"+86","code":"CN" },
AF: {"name":"Afghanistan","dial_code":"+93","code":"AF"}
};
var code = dialCodes.CN.dial_code;
Or
var myCode = 'CN'; // for example
var code = dialCodes[myCode].dial_code;
Since it's an array you can use filter to extract the data you need.
function getData(type, val) {
return dialCodes.filter(function (el) {
return el[type] === val;
})[0];
}
getData('code', 'CN').dial_code; // +86

Javascript Objects to XML String with multiple levels

I have a multi-dimensional Javascript Object that I can easily convert to a JSON string using a .stringify method. I'm trying to write a function to do something similar but in an XML, markup, format. The catch is I want it to be able to handle any number of dimensions.
Let's say I have the following the multi-dimensional object with values like so:
object['annualrevenues']['option0']['ID'] = 1;
object['annualrevenues']['option0']['text'] = '$50mil';
object['annualrevenues']['option1']['ID'] = 2;
object['annualrevenues']['option1']['text'] = '$100mil';
object['annualrevenues']['option2']['ID'] = 3;
object['annualrevenues']['option2']['text'] = '$200mil';
I want to build a string like so:
var xmlText = <xml><annualrevenues><option0><ID>1</ID><text>$50</text></option0></annualrevenues></xml>
That once returned as a response with contentType 'XMLDOC' will look like this:
<xml>
<annualrevenues>
<option0>
<ID>1</ID>
<text>$50</text>
</option0>
</annualrevenues>
</xml>
So I have the following function:
var xmlText = '<xml>';
xmlText += formatXMLSubObjects(objText,xmlText);
function formatXMLSubObjects(objText,xmlText){
for (prop in objText) {
if (typeof objText[prop] == 'object') {
xmlText += '<'+prop+'>';
for (subProp in objText[prop]) {
if (typeof objText[prop][subProp] == 'object') {
// Run the function again as recursion
xmlText += formatXMLSubObjects(objText[prop][subProp],xmlText);
}
else {
xmlText += '<' + subProp + '>' + objText[prop][subProp] + '</' + subProp + '>';
}
}
xmlText += '</'+prop+'>';
}
else {
xmlText += '<'+prop+'>'+objText[prop]+'</'+prop+'>';
}
}
return xmlText;
}
The problem is when the formatXMLSubObjects function returns from the second call, the original object in the first call has been overwritten and is now undefined.
Anyone able to help with this?
Move the definition of xmlText inside the function and use another variable outside to contain the initial payload, and also local variables in the for loops, otherwise they are considered global and overwritten, and don't pass your xmlText ahead to the call, but simply concatenate the result with the previous one every time.
function formatXMLSubObjects(objText) {
var xmlText = ""; // this will contain only this chunk of the object
for (var prop in objText) {
xmlText += '<'+prop+'>'; // place the tag anyway
if (typeof objText[prop] == 'object') {
xmlText += formatXMLSubObjects(objText[prop]); // if it's an object recurse
} else {
xmlText += objText[prop]; // ... otherwise just add the value (this will work only for simple values
}
xmlText += '</' + prop + '>';
}
return xmlText;
}
var xml = '<xml>';
xml += formatXMLSubObjects(obj);
xml += '</xml>';
Take a look at this fiddle: http://jsfiddle.net/vZjAP/

Categories