Calling variables outside of a function in javascript - javascript

I'm new to javascript and firebase. I would just like to ask if there is a chance to call my variables outside of my function?
Here is my sample code:
function gotData (data) {
console.log(data.val())
var promotions = data.val()
var keys = Object.keys(promotions)
console.log(keys)
for (var i = 0; i < keys.length; i++) {
var k = keys[i]
var name = promotions[k].promotionName
var description = promotions[k].description
var validityFrom = promotions[k].validityPeriodFrom
var validityTo = promotions[k].validityPeriodTo
var dateCreated = promotions[k].dateCreated
var dateUpdated = promotions[k].dateUpdated
console.log(name, description, validityFrom, validityTo, dateCreated, dateUpdated)
}
}
Can I call name, description, validityFrom, etc outside of the function gotData? I'll appreciate a help. Thank you in advance! :)

Define variable as global variable
//above function
var name, description, validityFrom, validityTo, dateCreated, dateUpdated;
function gotData (data) {
console.log(data.val())
var promotions = data.val()
var keys = Object.keys(promotions)
console.log(keys)
for (var i = 0; i < keys.length; i++) {
var k = keys[i]
name = promotions[k].promotionName
description = promotions[k].description
validityFrom = promotions[k].validityPeriodFrom
validityTo = promotions[k].validityPeriodTo
dateCreated = promotions[k].dateCreated
dateUpdated = promotions[k].dateUpdated
console.log(name, description, validityFrom, validityTo, dateCreated, dateUpdated)
}
}
// now you can access variables here
console.log(name, description, validityFrom, validityTo, dateCreated, dateUpdated)
EDIT
You can create an array to get all variables as you may have multidimensional data
var objData = [];
function gotData (data) {
console.log(data.val())
var promotions = data.val()
var keys = Object.keys(promotions)
for (var i = 0; i < keys.length; i++) {
var tempObj = [];
var k = keys[i]
tempObj['promotionName'] = promotions[k].promotionName;
tempObj['description'] = promotions[k].description;
tempObj['validityPeriodFrom'] = promotions[k].validityPeriodFrom;
tempObj['validityPeriodTo'] = promotions[k].validityPeriodTo;
tempObj['dateCreated'] = promotions[k].dateCreated;
tempObj['dateUpdated'] = promotions[k].dateUpdated;
objData.push(tempObj);
}
console.log(objData)
}

Related

App Script create array from email string

Using app scripts I'm trying to extract all the email addresses from email messages and put them in an array. From my console.log messages, I'm getting stuck because it looks like instead of an array I just get a string. i'm not too familiar with javascript. Any help would be great. I'm looking for an array of email address. The methods of message.get() return a string. I want to split out the email address and create a single, unified array.
var ui = SpreadsheetApp.getUi();
function onOpen(e){
ui.createMenu("Gmail Manager").addItem("Get Emails by Label", "getGmailEmails").addToUi();
}
function getGmailEmails(){
var label = GmailApp.getUserLabelByName("MyLabel");
var threads = label.getThreads();
var fullArray = [];
for(var i = threads.length - 1; i >=0; i--){
var messages = threads[i].getMessages();
for (var j = 0; j <messages.length; j++){
var message = messages[j];
if (message.isUnread()){
fullArray.push(extractDetails(message));
}
}
}
console.log("FullArray:"+fullArray);
for(var i=0; i<fullArray.length; i++){
console.log("printing array " + i + ": "+fullArray[i])
}
}
function extractDetails(message){
var dateTime = message.getDate();
var subjectText = message.getSubject();
var senderDetails = message.getFrom();
var ccEmails = message.getCc();
var replyEmail = message.getReplyTo();
var toEmail = message.getTo();
var emailArray = []
var senderArray = senderDetails.split(',');
var ccArray = ccEmails.split(',');
var replyArray = replyEmail.split(',');
var toArray = toEmail.split(',');
for (var i =0 ; i<toArray.length; i++){
console.log("toArray Loop"+ i + " : "+ toArray[i]);
emailArray.push([toArray[i]]);
}
for (var i =0 ; i<ccArray.length; i++){
console.log("ccArray Loop"+ i + " : "+ ccArray[i]);
emailArray.push([ccArray[i]]);
}
console.log("Email Array: "+ emailArray);
var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
activeSheet.appendRow([dateTime, senderDetails, subjectText, ccEmails,replyEmail,toEmail,emailArray]);
return emailArray;
}
I think the problem is just the console output. If you change console.log("Email Array: "+ emailArray); to console.log("Email Array: ", emailArray);, then it shows an array of arrays. You could simplify your extract method as follows:
function extractDetails(message) {
/* ... */
var senderDetails = message.getFrom();
var ccEmails = message.getCc();
var replyEmails = message.getReplyTo();
var toEmails = message.getTo();
let emailArray = [senderDetails, ccEmails, replyEmails, toEmails].reduce(
(array, string) => {
//remove names (like "Name <name#company.com>") and filter empty values
let emails = string
.split(/\s*,\s*/)
.map(e => e.replace(/.*?([^#<\s]+#[^#\s>]+).*?/g, "$1"))
.filter(Boolean);
if(emails.length > 0)
return array.concat(emails)
return array
}, []);
/* ... */
}

Javascript I can take Filelist but I cant take file

I want take file from filelist but I cant take. How can I make
FileList (inputs[key].files)
FileList (inputs[key].files[0])
var inputs;
inputs = document.getElementsByTagName('input');
inputs = Array.prototype.slice.call(inputs);
var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
for (var i = 0; i <= buttonsCount; i += 1) {
buttons[i].onclick = function(e) {
var userid = document.querySelector('.userid').innerHTML;
var raffleid = this.id;
var finish = this.value;
if (finish) {
postFinish(userid, raffleid, finish)
}
for (var key in inputs) {
var value = inputs[key].value;
var file = inputs[key].files;
var name = inputs[key].name;
if (value) {
console.log('file: ', file)
postData(raffleid, name, value, userid, file)
}
}
};
}
If I understand correctly, your code is working and you just want to access the Object?
Then try this:
const myArray = Object.values(FileList)
This returns an array of Objects, which you could access with
myArray[0]

split json into carousel cards

I get the results from a JSON file and I want to display it in carousel,
how can I do it?
Here is the code:
var req = http.request(options, function (res) {
console.log('STATUS: ' + res.statusCode);
if (res.statusCode !== 201) {
session.send("Sorry, service is not reachable at the moment, please try again later");
}
//session.send(res.statusCode.toString());
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
var json = chunk.toString();
var graph = JSON.parse(json);
var attachmentList = [];
for (var i = 0; i < graph.clauses.length; i++) {
var obj = graph.clauses[i];
console.log(obj);
var clause_id;
var clause_text;
for (var key in obj) {
clause_id = key;
clause_text = obj[key].toString();
// session.send(clause_id+"<br>"+clause_text);
}
let card = new botbuilder_1.HeroCard(session)
.title(clause_id)
.subtitle(clause_text)
.buttons([botbuilder_1.CardAction.imBack(session, 'Mark as Relevant', 'Mark as Relevant')]);
let msg = new botbuilder_1.Message(session);
msg.attachmentLayout(botbuilder_1.AttachmentLayout.carousel);
msg.attachments([card]);
session.send(msg);
// session.endDialog(msg);
}
});
});
Here is the screenshot of the results:
You're sending a message on each iteration of the for loop, and each message only has one attachment. Try sending one message after the for loop and give that message the whole list of attachments.
var attachmentList = [];
for (var i = 0; i < graph.clauses.length; i++) {
var obj = graph.clauses[i];
console.log(obj);
var clause_id;
var clause_text;
for (var key in obj) {
clause_id = key;
clause_text = obj[key].toString();
// session.send(clause_id+"<br>"+clause_text);
}
let card = new botbuilder_1.HeroCard(session)
.title(clause_id)
.subtitle(clause_text)
.buttons([botbuilder_1.CardAction.imBack(session, 'Mark as Relevant', 'Mark as Relevant')]);
attachmentList.push(card);
}
let msg = new botbuilder_1.Message(session);
msg.attachmentLayout(botbuilder_1.AttachmentLayout.carousel);
msg.attachments(attachmentList);
session.send(msg);

change JSON response in javascript

I am working on WEB API's, I have received the JSON response from server, NOW I want to change the returned response into different JSON's to show different table and graphs.
this is the response from server
{"data":[{"id":3663101,"lstImeis":[{"number":"14370340908558","maxDate":"2017-08-24 22:08:58.0","minDate":"2017-08-24 22:08:58.0"},{"number":"22418344742097","maxDate":"2017-08-24 18:08:56.0","minDate":"2017-08-24 18:08:56.0"}],"number2":789},{"id":3665337,"lstImeis":[{"number":"48717031235502","maxDate":"2017-08-24 21:09:38.0","minDate":"2017-08-24 21:09:38.0"},{"number":"42540009239622","maxDate":"2017-08-24 16:35:08.0","minDate":"2017-08-24 16:35:08.0"},{"number":"42540009239644","maxDate":"2017-08-24 16:35:08.0","minDate":"2017-08-24 16:35:08.0"}],"number2":456}]}
and I need to convert this response to look like this :
{"data":[{"id":3663101,"number":"14370340908558","maxDate":"2017-08-24 22:08:58.0","minDate":"2017-08-24 22:08:58.0","number2":789},{"id":3663101,"number":"22418344742097","maxDate":"2017-08-24 18:08:56.0","minDate":"2017-08-24 18:08:56.0","number2":789},{"id":3665337,"number":"48717031235502","maxDate":"2017-08-24 21:09:38.0","minDate":"2017-08-24 21:09:38.0","number2":456},{"id":3665337,"number":"42540009239622","maxDate":"2017-08-24 16:35:08.0","minDate":"2017-08-24 16:35:08.0","number2":456},{"id":3665337,"number":"42540009239644","maxDate":"2017-08-24 16:35:08.0","minDate":"2017-08-24 16:35:08.0","number2":456}]}
this is what I have done so far,
var data = new Array();
var str = '{"data":[{"id":3663101,"lstImeis":[{"number":"14370340908558","maxDate":"2017-08-24 22:08:58.0","minDate":"2017-08-24 22:08:58.0"},{"number":"22418344742097","maxDate":"2017-08-24 18:08:56.0","minDate":"2017-08-24 18:08:56.0"}],"number2":789},{"id":3665337,"lstImeis":[{"number":"48717031235502","maxDate":"2017-08-24 21:09:38.0","minDate":"2017-08-24 21:09:38.0"},{"number":"42540009239622","maxDate":"2017-08-24 16:35:08.0","minDate":"2017-08-24 16:35:08.0"},{"number":"42540009239644","maxDate":"2017-08-24 16:35:08.0","minDate":"2017-08-24 16:35:08.0"}],"number2":456}]}';
var response = JSON.parse(str);
var tableData = response.data;
var dataLength = response.data.length;
for (i = 0; i < dataLength; i++) {
var obj = {};
obj["id"] = tableData[i].id;
for (a = 0; a < tableData[i].lstImeis.length; a++) {
obj["number"] = tableData[i].lstImeis[a].number,
obj["maxDate"] = tableData[i].lstImeis[a].maxDate,
obj["minDate"] = tableData[i].lstImeis[a].minDate
}
obj["number2"] = tableData[i].number2;
data.push(obj);
}
console.log(JSON.stringify(data));
Here is JSFIDDLE
Outer loops works fines but inner loop gives the last updated data, If you look at the given data and changed data, you will see the difference.
Any idea, why its overriding the values in inner for loop and appending only last values into obj?
Your logic is incorrect line
var obj = {};
obj["id"] = tableData[i].id;
should be inside the inner loop. also line
obj["number2"] = tableData[i].number2;
data.push(obj);
should be moved inside the inner loop.
Here is the improved and working code https://jsfiddle.net/dmtfxt35/4/
var response = JSON.parse(str);
var tableData = response.data;
var finalObj = {data:[]};
for (var i in tableData){
for(var a in tableData[i].lstImeis){
var tmpObj = {};
tmpObj['id'] = tableData[i].id;
tmpObj["number"] = tableData[i].lstImeis[a].number;
tmpObj["maxDate"] = tableData[i].lstImeis[a].maxDate;
tmpObj["minDate"] = tableData[i].lstImeis[a].minDate;
tmpObj["number2"] = tableData[i].number2;
finalObj.data.push(tmpObj);
}
}
console.log(JSON.stringify(finalObj));
I hope this helped.
You using the same obj variable while inserting the data to array.
Obj is dict and it got updated on loop.
I have updated the code as per you requirement
<script>
var data = new Array();
var str = '{"msg":"success","code":"200","status":null,"data":[{"id":3663101,"lstImeis":[{"number":"14370340908558","maxDate":"2017-08-24 22:08:58.0","minDate":"2017-08-24 22:08:58.0"},{"number":"22418344742097","maxDate":"2017-08-24 18:08:56.0","minDate":"2017-08-24 18:08:56.0"}],"number2":789},{"id":3665337,"lstImeis":[{"number":"48717031235502","maxDate":"2017-08-24 21:09:38.0","minDate":"2017-08-24 21:09:38.0"},{"number":"42540009239622","maxDate":"2017-08-24 16:35:08.0","minDate":"2017-08-24 16:35:08.0"},{"number":"42540009239644","maxDate":"2017-08-24 16:35:08.0","minDate":"2017-08-24 16:35:08.0"}],"number2":456}],"draw":0,"limit":0,"recordsFiltered":0,"recordsTotal":0}';
var response = JSON.parse(str);
var tableData = response.data;
var dataLength = response.data.length;
for(i = 0; i < dataLength; i++){
for(a = 0; a < tableData[i].lstImeis.length; a++){
var obj = {};
obj["id"] = tableData[i].id;
obj["number"] = tableData[i].lstImeis[a].number;
obj["maxDate"] = tableData[i].lstImeis[a].maxDate;
obj["minDate"] = tableData[i].lstImeis[a].minDate;
obj["number2"] = tableData[i].number2;
data.push(obj);
}
}
console.log(JSON.stringify(data));
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can use array#reduce and array#map.
var response = [{"id":3663101,"lstImeis":[{"number":"14370340908558","maxDate":"2017-08-24 22:08:58.0","minDate":"2017-08-24 22:08:58.0"},{"number":"22418344742097","maxDate":"2017-08-24 18:08:56.0","minDate":"2017-08-24 18:08:56.0"}],"number2":789},{"id":3665337,"lstImeis":[{"number":"48717031235502","maxDate":"2017-08-24 21:09:38.0","minDate":"2017-08-24 21:09:38.0"},{"number":"42540009239622","maxDate":"2017-08-24 16:35:08.0","minDate":"2017-08-24 16:35:08.0"},{"number":"42540009239644","maxDate":"2017-08-24 16:35:08.0","minDate":"2017-08-24 16:35:08.0"}],"number2":456}];
var result = response.reduce(function(res, obj) {
var temp = obj.lstImeis.map(function(o) {
return Object.assign({}, o, {id: obj.id, number2: obj.number2});
});
return res.concat(temp);
},[])
var output = {data: result};
console.log(JSON.stringify(output));
Look at this Fiddle. You were pushing last updated obj data. You had to push obj each time you update it.
for(i = 0; i < dataLength; i++){
for(a = 0; a < tableData[i].lstImeis.length; a++){
var obj = {};
obj["id"] = tableData[i].id;
obj["number"] = tableData[i].lstImeis[a].number;
obj["maxDate"] = tableData[i].lstImeis[a].maxDate;
obj["minDate"] = tableData[i].lstImeis[a].minDate;
obj["number2"] = tableData[i].number2;
data.push(obj);
}
}

Wait Callback and our result data to take another proccess out of this function

i have this class (product).
var Product = function () {
this.products = [];
this.priceFrom = null;
this.priceTo = null;
this.countDone = 0;
};
Product.prototype = {
constructor: Product,
getProductsByPriceRange: function (priceFrom, priceTo) {
var xhrUrl = "<?= base_url('market/products/xhr_product_price_range') ?>";
var xhrData = {price_from: priceFrom, price_to: priceTo};
var xhrType = "json";
var UtilsClass = new Utils();
UtilsClass.xhrConnection(xhrUrl, xhrData, xhrType, function (data) {
/* MY DATA IS HERE */
});
},
buildList:function (products) {
for (var i = 0; i < products.length; i++) {
var product = products[i];
console.log("product");
}
},
buildOne: function (product) {
}
};
/*....more classes */
And another piece of code (out of product class):
var fromPrice = data.from;
var toPrice = data.to;
var ProductClass = new Product();
var lastCountDone = ProductClass.countDone;
ProductClass.priceFrom = fromPrice;
ProductClass.priceTo = toPrice;
var myProducts = ProductClass.getProductsByPriceRange(ProductClass.priceFrom, ProductClass.priceTo);
My question is... can i wait callback of UtilsClass.xhrConnection (in first piece) and use generated data of callback in second piece of code (out of first piece).
Any ideas would be very valuable to me. Thank you!
var Product = function () {
this.products = [];
this.priceFrom = null;
this.priceTo = null;
this.countDone = 0;
};
Product.prototype = {
constructor: Product,
getProductsByPriceRange: function (priceFrom, priceTo) {
var xhrUrl = "<?= base_url('market/products/xhr_product_price_range') ?>";
var xhrData = {price_from: priceFrom, price_to: priceTo};
var xhrType = "json";
var UtilsClass = new Utils();
return new Promise(function(resolve, reject){
UtilsClass.xhrConnection(xhrUrl, xhrData, xhrType, function (data) {
/* MY DATA IS HERE */
resolve(data)
});
});
},
buildList:function (products) {
for (var i = 0; i < products.length; i++) {
var product = products[i];
console.log("product");
}
},
buildOne: function (product) {
}
};
While calling,
var fromPrice = data.from;
var toPrice = data.to;
var ProductClass = new Product();
var lastCountDone = ProductClass.countDone;
ProductClass.priceFrom = fromPrice;
ProductClass.priceTo = toPrice;
var myProducts = ProductClass.getProductsByPriceRange(ProductClass.priceFrom, ProductClass.priceTo).then(function(data){%your data will be available here%});

Categories

Resources