For loop not iterating a variable - javascript

I'm just learning javascript and I'm trying to update woocommerce products through GAS.
The issue in question is the following:
I have a variable that parses the response from woocommerce
for (let sku of skuSearch) {
var surl = website + "/wp-json/wc/v3/products?consumer_key=" + ck + "&consumer_secret=" + cs + "&sku=" + sku;
var url = surl
Logger.log(url)
var result = UrlFetchApp.fetch(url, optionsGet);
if (result.getResponseCode() == 200) {
var wooProducts = JSON.parse(result.getContentText());
Logger.log(result.getContentText());
}
Then I have another for to iterate and from a new array that contains id + sku of wooProducts and price from a different variable that takes the updated price from my sheet:
var idLength = wooProducts.length;
Logger.log(idLength);
for (var i = 0; i < idLength; i++) {
var container = [];
Logger.log(i);
container.push({
id: wooProducts[i]["id"],
sku: wooProducts[i]["sku"],
price: data[i]["price"],
});
I can't tell exactly why it doesn't work. I mean the for loop works, it pushes id, sku and price in every loop, it's just that data[i] only provides the first ¿object? instead of looping like wooProducts which add +1 at every loop.
I'll copy 3 loops so it's crystal clear, I'm not sure it's already clear.
Loop 1:
[{"id":1622,"sku":"PD-1000-B","price":8145.9}]
Loop 2:
[{"id":1624,"sku":"PD-1007-A","price":8145.9}]
Loop 3:
[{"id":1625,"sku":"PD-1014","price":8145.9}]
As you can see id+sku change but price doesn't.
For further context, I'll include the data variable that is declaed outside the For:
const data = codigos.map(function(codigos, indice) {
return {
sku: codigos[0],
price: precios[indice][0]
}
})
//** EDIT:
I'm adding the entire code so it makes more sense maybe?
function getDataloopwoo() {
var ck = 'xxx'
var cs = 'xxx'
var website = 'xxx'
var optionsGet =
{
"method": "GET",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"muteHttpExceptions": true,
};
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('PreciosBULK');
var codigos = sheet.getRange("A2:A").getValues();
var precios = sheet.getRange("B2:B").getValues();
var skuSearch = sheet.getRange("A2:A").getValues();
const data = codigos.map(function(codigos, indice) {
return {
sku: codigos[0],
price: precios[indice][0]
}
})
Logger.log(skuSearch)
for (let sku of skuSearch) {
var surl = website + "/wp-json/wc/v3/products?consumer_key=" + ck + "&consumer_secret=" + cs + "&sku=" + sku;
var url = surl
Logger.log(url)
var result = UrlFetchApp.fetch(url, optionsGet);
if (result.getResponseCode() == 200) {
var wooProducts = JSON.parse(result.getContentText());
Logger.log(result.getContentText());
}
var idLength = wooProducts.length;
Logger.log(idLength);
var container = [];
for (var i = 0; i < idLength; i++) {
Logger.log(i);
container.push({
id: wooProducts[i]["id"],
sku: wooProducts[i]["sku"],
price: data[i]["price"],
});
Logger.log(container);
var wooBatch = JSON.stringify(container);
Logger.log(wooBatch);
}
}
}
// FINAL EDIT with "solve":
So I figured it was inefficient to ask by 1 sku at a time, so now I'm asking by the 100, and paginating with a while if and saving id, sku, price to the container array.
I will need now to compare the container array to the array with the updated prices and form a new array with id, sku and updated price, I'm reading up on that right now. The code:
function getDataloopwoo() {
var ck = 'xx'
var cs = 'xx'
var website = 'xx'
var optionsGet =
{
"method": "GET",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"muteHttpExceptions": true,
};
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('PreciosBULK');
var codigos = sheet.getRange("A2:A").getValues();
var precios = sheet.getRange("B2:B").getValues();
const data = codigos.map(function(codigos, indice) {
return {
sku: codigos[0],
price: precios[indice][0]
}
})
var container = [];
var surl = website + "/wp-json/wc/v3/products?consumer_key=" + ck + "&consumer_secret=" + cs + "&per_page=100";
var url = surl
//Logger.log(url)
var result = UrlFetchApp.fetch(url, optionsGet);
var headers = result.getAllHeaders();
var total_pages = headers['x-wp-totalpages'];
var pages_count = 0;
while (pages_count < total_pages) {
if (result.getResponseCode() == 200) {
var wooProducts = JSON.parse(result.getContentText());
//Logger.log(result.getContentText());
}
for (var i = 0; i < wooProducts.length; i++) {
//Logger.log(i);
container.push({
id: wooProducts[i]["id"],
sku: wooProducts[i]["sku"],
price: wooProducts[i]["price"],
});
Logger.log(container);
}
pages_count++;
if (pages_count < total_pages){
var surl = website + "/wp-json/wc/v3/products?consumer_key=" + ck + "&consumer_secret=" + cs + "&per_page=100" + "&page=" + (pages_count + 1);
var url = surl
var result = UrlFetchApp.fetch(url, optionsGet);
Logger.log(url);
}
}
}

You're reseting the array container in every iteration of the loop:
for (var i = 0; i < idLength; i++) {
var container = []; // <-----------------here
...
container.push({
...
I think the array should be defined outside the loop:
var container = [];
for (var i = 0; i < idLength; i++) {
...
container.push({
...

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
}, []);
/* ... */
}

How i can get bigquery table data in google script?

I want to bigquery table data using app script ,I am using this code but i am getting job id, i dont job id i want table data please help me this.
function runQuery() {
DriveApp.getRootFolder();
var projectId = 'imran-338706';
var request = {
query: 'SELECT network_affiliate_name FROM `imran-338706.imranabc.bhk` LIMIT 10',
useLegacySql: false
}
var queryResults = BigQuery.Jobs.query(request, projectId);
var jobId = queryResults.jobReference.jobId;
console.log(queryResults)
}
I verified using the following code for queries returning small amount of data :
function runQuery() {
DriveApp.getRootFolder();
var projectId = ProjectID;
var request = {
query: 'SELECT * from `bigquery-public-data.austin_311.311_service_requests` limit 2',
useLegacySql: false
}
var queryResults = BigQuery.Jobs.query(request, projectId);
var jobId = queryResults.jobReference.jobId;
var rows = queryResults.rows;
var header = "";
for (var i = 0; i < queryResults.schema.fields.length; i++){
header+= " " + queryResults.schema.fields[i].name;
}
console.log(header)
var data = new Array(rows.length);
var string = ""
for (var i = 0; i < rows.length; i++) {
var cols = rows[i].f;
data[i] = new Array(cols.length);
for (var j = 0; j < cols.length; j++) {
data[i][j]= cols[j].v;
string+= " "+ data[i][j]
}
console.log(string);
}
}
It gave the schema and row contents:

How to do page break when exporting google sheet into PDF

I want to export the current google sheet data into pdf page but I do want a page break at row 10 so that any data after row 10 goes on to the next page. This means there will be multiple pages for more data. I do not want to print all data on one page. The final pdf file should have multiple pages for data that crosses row 10 in the google sheet
var saveToRootFolder = false
function onOpen() {
SpreadsheetApp.getUi()
.createAddonMenu()
.addItem('Export all sheets', 'exportAsPDF')
.addItem('Export all sheets as separate files', 'exportAllSheetsAsSeparatePDFs')
.addItem('Export current sheet', 'exportCurrentSheetAsPDF')
.addItem('Export selected area', 'exportPartAsPDF')
.addItem('Export predefined area', 'exportNamedRangesAsPDF')
.addToUi()
}
function _exportBlob(blob, fileName, spreadsheet) {
blob = blob.setName(SpreadsheetApp.getActiveSheet().getRange('E4:G4').getValue())
var folder = saveToRootFolder ? DriveApp : DriveApp.getFileById(spreadsheet.getId()).getParents().next()
var pdfFile = folder.createFile(blob)
var folder = DriveApp.getFolderById("FOLDER_ID");
pdfFile.moveTo(folder);
// Display a modal dialog box with custom HtmlService content.
const htmlOutput = HtmlService
.createHtmlOutput('<p>Click to open ' + fileName + '</p>')
.setWidth(300)
.setHeight(80)
SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Export Successful')
}
function exportAsPDF() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet()
var blob = _getAsBlob(spreadsheet.getUrl())
_exportBlob(blob, spreadsheet.getName(), spreadsheet)
}
function _getAsBlob(url, sheet, range) {
var rangeParam = ''
var sheetParam = ''
if (range) {
rangeParam =
'&r1=' + (range.getRow() - 1)
+ '&r2=' + range.getLastRow()
+ '&c1=' + (range.getColumn() - 1)
+ '&c2=' + range.getLastColumn()
}
if (sheet) {
sheetParam = '&gid=' + sheet.getSheetId()
}
// A credit to https://gist.github.com/Spencer-Easton/78f9867a691e549c9c70
// these parameters are reverse-engineered (not officially documented by Google)
// they may break overtime.
var exportUrl = url.replace(/\/edit.*$/, '')
+ '/export?exportFormat=pdf&format=pdf'
+ '&size=A4'
+ '&portrait=true'
+ '&fitw=true'
+ '&top_margin=0.2'
+ '&bottom_margin=0.2'
+ '&left_margin=0.2'
+ '&right_margin=0.1'
+ '&scale=3'
+ '&sheetnames=false&printtitle=false'
+ '&pagenum=UNDEFINED' // change it to CENTER to print page numbers
+ '&gridlines=true'
+ '&fzr=FALSE'
+ sheetParam
+ rangeParam
Logger.log('exportUrl=' + exportUrl)
var response
var i = 0
for (; i < 5; i += 1) {
response = UrlFetchApp.fetch(exportUrl, {
muteHttpExceptions: true,
headers: {
Authorization: 'Bearer ' + ScriptApp.getOAuthToken(),
},
})
if (response.getResponseCode() === 429) {
// printing too fast, retrying
Utilities.sleep(3000)
} else {
break
}
}
if (i === 5) {
throw new Error('Printing failed. Too many sheets to print.')
}
return response.getBlob()
}
function exportAllSheetsAsSeparatePDFs() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet()
var files = []
var folder = saveToRootFolder ? DriveApp : DriveApp.getFileById(spreadsheet.getId()).getParents().next()
spreadsheet.getSheets().forEach(function (sheet) {
spreadsheet.setActiveSheet(sheet)
var blob = _getAsBlob(spreadsheet.getUrl(), sheet)
var fileName = sheet.getName()
blob = blob.setName(fileName)
var pdfFile = folder.createFile(blob)
files.push({
url: pdfFile.getUrl(),
name: fileName,
})
})
const htmlOutput = HtmlService
.createHtmlOutput('<p>Click to open PDF files</p>'
+ '<ul>'
+ files.reduce(function (prev, file) {
prev += '<li>' + file.name + '</li>'
return prev
}, '')
+ '</ul>')
.setWidth(300)
.setHeight(150)
SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Export Successful')
}
function exportCurrentSheetAsPDF() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet()
var currentSheet = SpreadsheetApp.getActiveSheet()
var blob = _getAsBlob(spreadsheet.getUrl(), currentSheet)
_exportBlob(blob, currentSheet.getName(), spreadsheet)
}
function exportPartAsPDF(predefinedRanges) {
var ui = SpreadsheetApp.getUi()
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet()
var selectedRanges
var fileSuffix
if (predefinedRanges) {
selectedRanges = predefinedRanges
fileSuffix = '-predefined'
} else {
var activeRangeList = spreadsheet.getActiveRangeList()
if (!activeRangeList) {
ui.alert('Please select at least one range to export')
return
}
selectedRanges = activeRangeList.getRanges()
fileSuffix = '-selected'
}
if (selectedRanges.length === 1) {
// special export with formatting
var currentSheet = selectedRanges[0].getSheet()
var blob = _getAsBlob(spreadsheet.getUrl(), currentSheet, selectedRanges[0])
var fileName = spreadsheet.getName() + fileSuffix
_exportBlob(blob, fileName, spreadsheet)
return
}
var tempSpreadsheet = SpreadsheetApp.create(spreadsheet.getName() + fileSuffix)
if (!saveToRootFolder) {
DriveApp.getFileById(tempSpreadsheet.getId()).moveTo(DriveApp.getFileById(spreadsheet.getId()).getParents().next())
}
var tempSheets = tempSpreadsheet.getSheets()
var sheet1 = tempSheets.length > 0 ? tempSheets[0] : undefined
SpreadsheetApp.setActiveSpreadsheet(tempSpreadsheet)
tempSpreadsheet.setSpreadsheetTimeZone(spreadsheet.getSpreadsheetTimeZone())
tempSpreadsheet.setSpreadsheetLocale(spreadsheet.getSpreadsheetLocale())
for (var i = 0; i < selectedRanges.length; i++) {
var selectedRange = selectedRanges[i]
var originalSheet = selectedRange.getSheet()
var originalSheetName = originalSheet.getName()
var destSheet = tempSpreadsheet.getSheetByName(originalSheetName)
if (!destSheet) {
destSheet = tempSpreadsheet.insertSheet(originalSheetName)
}
Logger.log('a1notation=' + selectedRange.getA1Notation())
var destRange = destSheet.getRange(selectedRange.getA1Notation())
destRange.setValues(selectedRange.getValues())
destRange.setTextStyles(selectedRange.getTextStyles())
destRange.setBackgrounds(selectedRange.getBackgrounds())
destRange.setFontColors(selectedRange.getFontColors())
destRange.setFontFamilies(selectedRange.getFontFamilies())
destRange.setFontLines(selectedRange.getFontLines())
destRange.setFontStyles(selectedRange.getFontStyles())
destRange.setFontWeights(selectedRange.getFontWeights())
destRange.setHorizontalAlignments(selectedRange.getHorizontalAlignments())
destRange.setNumberFormats(selectedRange.getNumberFormats())
destRange.setTextDirections(selectedRange.getTextDirections())
destRange.setTextRotations(selectedRange.getTextRotations())
destRange.setVerticalAlignments(selectedRange.getVerticalAlignments())
destRange.setWrapStrategies(selectedRange.getWrapStrategies())
}
// remove empty Sheet1
if (sheet1) {
Logger.log('lastcol = ' + sheet1.getLastColumn() + ',lastrow=' + sheet1.getLastRow())
if (sheet1 && sheet1.getLastColumn() === 0 && sheet1.getLastRow() === 0) {
tempSpreadsheet.deleteSheet(sheet1)
}
}
exportAsPDF()
SpreadsheetApp.setActiveSpreadsheet(spreadsheet)
DriveApp.getFileById(tempSpreadsheet.getId()).setTrashed(true)
}
function exportNamedRangesAsPDF() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet()
var allNamedRanges = spreadsheet.getNamedRanges()
var toPrintNamedRanges = []
for (var i = 0; i < allNamedRanges.length; i++) {
var namedRange = allNamedRanges[i]
if (/^print_area_.*$/.test(namedRange.getName())) {
Logger.log('found named range ' + namedRange.getName())
toPrintNamedRanges.push(namedRange.getRange())
}
}
if (toPrintNamedRanges.length === 0) {
SpreadsheetApp.getUi().alert('No print areas found. Please add at least one \'print_area_1\' named range in the menu Data > Named ranges.')
return
} else {
toPrintNamedRanges.sort(function (a, b) {
return a.getSheet().getIndex() - b.getSheet().getIndex()
})
exportPartAsPDF(toPrintNamedRanges)
}
}
I developed an example script to test the approach described in my comment. I'll leave it here for future reference, but feel free to leave a comment if you have any doubt about it. This is the final script:
function exportRowsToPDF() {
var importantRows = [2, 13, 14, 15, 19]; // Exported rows
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var originalSheet = SpreadsheetApp.getActiveSheet();
var sheets = spreadsheet.getSheets();
var tempSheet = spreadsheet.insertSheet("TEMP", 10);
var maxColumn = originalSheet.getLastColumn();
for (var i = 0; i < importantRows.length; i++) {
tempSheet.appendRow(originalSheet.getRange(importantRows[i], 1, 1, maxColumn)
.getValues()[0]);
}
for (var i = 0; i < sheets.length; i++) {
if (sheets[i].getSheetName() !== "TEMP") {
sheets[i].hideSheet();
}
}
DriveApp.createFile(spreadsheet.getBlob().setName("Exported Sheet"));
for (var i = 0; i < sheets.length; i++) {
sheets[i].showSheet();
}
spreadsheet.deleteSheet(tempSheet);
}
You can modify the script to export any particular rows, but I used five of them for testing. This script will create a new sheet on your spreadsheet, and it will copy any relevant row there. Then, it will hide every sheet minus the newly created one. After that it will export the spreadsheet as a PDF blob directly to your Drive. Finally, it will reset the spreadsheet to the original state (by removing the created sheet and unhiding every other sheet). This code uses the same methods as your example, but write to me if you want to clarify any point.

Google sheets incorrect range width when no cmc matches

I am using this function to pull information from coinmarketcap using their v2 api. The problem I am getting is that if a "website_slug" does not exist on coinmarketcap, I get an incorrect range width error instead of the function just putting xxx in the cell. This can be recreated by having a cell in column B that doesn't match a website_slug on cmc (https://api.coinmarketcap.com/v2/ticker/).
function getMarketCap(sheetname) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sheetname);
var assets = [];
var idRange = sheet.getRange("B1:B");
var lastRow = getLastRowOfRange(idRange);
var cellRange = sheet.getRange(1, 2, lastRow).getValues();
var mcRange = sheet.getRange(1, 3, lastRow);
var mcValues = [];
for (var i = 0; i < cellRange.length; i++) {
assets[i] = cellRange[i];
}
var req = [];
for (var i = 0; i < 16; i++) {
req.push({
muteHttpExceptions: true,
method: "get",
url: "https://api.coinmarketcap.com/v2/ticker/?start=" + (i * 100 + 1),
});
}
var responses = UrlFetchApp.fetchAll(req);
var res = responses.filter(function(e){return e.getResponseCode() == 200}).map(function(e){return JSON.parse(e.getContentText())});
if (responses.length != res.length) Logger.log("%s errors occurred.", responses.length - res.length);
var mcValues = [];
assets.forEach(function(e, h) {
mcValues[h] = []
res.some(function(f) {
Object.keys(f.data).some(function(g) {
if (f.data[g].website_slug == e[0]) {
mcValues[h][0] = f.data[g].quotes.USD.market_cap;
return true;
}
});
if (mcValues[h][0]) return true;
});
if (!mcValues[h][0]) mcValues[h][0] = 'xxx';
});
mcRange.setValues(mcValues);
}

Count how many times i have the same word

My variable tag returns one of these 4 different values: assistance, bug, evolution or maintenance. I would like to count how many times I have each of those words. I would like to display how many times I have each of those item in my console first. I really don't know how to do that. Here is my code :
function displaytickets(y){
$.ajax({
url: "https://cubber.zendesk.com/api/v2/users/" + y + "/tickets/requested.json?per_page=150",
type: 'GET',
dataType: 'json',
cors: true ,
contentType: 'application/json',
secure: true,
beforeSend: function(xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(""));
},
success: function(data) {
var sortbydate = data.tickets.sort(function(a, b){
return new Date(b.created_at) - new Date(a.created_at);
});
var ids = $.map(data.tickets, function (data) {
return data.id;
})
localStorage.setItem("mesid", ids);
for (i = 0; i < data.tickets.length; i++) {
var myticket = data.tickets[i];
var mydate = data.tickets[i].created_at;
var created = moment(mydate).format("MM-DD-YY");
var mytitle = data.tickets[i].subject;
var description = data.tickets[i].description;
var status = data.tickets[i].status;
var tag = data.tickets[i].tags[0];
console.log(tag);
var myid = data.tickets[i].id;
}
var nbticket = data.tickets.length;
$("#name").append('<h2 class="title">' + " " + nbticket + " ticket(s)" + '</h2>');
},
});
}
Here's what I get from the console for the console.log(tag):
You can achieve this by using an object to store the occurrence count, keyed by the string itself. Try this:
var occurrences = {};
Then in your success handler you can add and increment the tags as you find them:
success: function(data) {
// your code here...
for (i = 0; i < data.tickets.length; i++) {
// your code here...
var tag = data.tickets[i].tags[0];
if (occurrences.hasOwnProperty(tag)) {
occurrences[tag]++;
} else {
occurrences[tag] = 1;
}
}
console.log(occurrences);
},
Working example
Did you try to count it in your for loop ?
var maintenance_counter = 0;
for (i = 0; i < data.tickets.length; i++) {
var myticket = data.tickets[i];
var mydate = data.tickets[i].created_at;
var created = moment(mydate).format("MM-DD-YY");
var mytitle = data.tickets[i].subject;
var description = data.tickets[i].description;
var status = data.tickets[i].status;
var tag = data.tickets[i].tags[0];
var myid = data.tickets[i].id;
if( tag == "maintenance" ){
maintenance_counter++;
}
}
alert("Total maintenance occurrence:"+ maintenance_counter);
Create an object to hold your tag result count, similar to this:
var tagCount = {};
for (i = 0; i < data.tickets.length; i++) {
var tag = data.tickets[i].tags[0];
if (tagCount[tag] === undefined) {
tagCount[tag] = 1;
} else {
tagCount[tag] += 1;
}
}
console.log(tagCount);

Categories

Resources