Object at different indexes when exporting in json - arrays

It happens that I am creating an object in Node JS and mssq, however some arrays are put in position 0, 0, and other arrays are put in [0], 1, 2, How can I find out what is causing this behavior?
Behavior 1
Query
var branchOfficesDTO = [];
var branchs = await pool.request().input('idUser', idUser).query(queryGetBranchsByUser);
for (let i = 0; i < branchs.recordset.length; i++) {
var categories = await pool.request().input('id', branchs.recordset[i].id).query(queryGetCategoriesByBranch);
let userDTO = {
categories: categories.recordset
}
branchOfficesDTO.push(branchOfficeDTO);
}
Result
Behavior 2
Query
var usersDTOByID = [];
var users = await pool.request().input('id', id).query(queryGetUserById);
for (let i = 0; i < users.recordset.length; i++) {
var categories = await pool.request().input('idUser', users.recordset[i].id).query(queryGetCategoriesByUser);
let userDTO = { categories: categories.recordset }
}
usersDTOByID.push(userDTO);
Result
I need the second behavior, help

Related

I dont understand what is wrong with this code

My code is used so it generates random rarities based on how many you want to generate but I keep getting the syntax error:
i is not defined
With this code:
var rarities = [
'Common',
'Uncommon',
'Rare',
'Epic',
'Legendary',
'Exotic',
'Mythic'
]
let rarity = rarities[Math.floor(Math.random() * rarities.length)
function generateRarity(length, times){
let numbers = [];
for(i=0; i < times; i++){
let number = Math.floor(Math.random() * length)
numbers.push(number)
}
return numbers;
}
let indexArray = generateRarity(rarities.length, args)
let generatedRarities = [];
indexArray.forEach(index => generatedRarities.push(rarities[index]))
sentrarities = "#".join(generatedRarities)
await message.reply(sentrarities)
You get this error only because of a typo. When you are declaring let rarities, you are missing an ] at the end of it. JS then tries to include the function in it but then finds out that it can't so the error comes. All you have to do is change your code to:
var rarities = [
'Common',
'Uncommon',
'Rare',
'Epic',
'Legendary',
'Exotic',
'Mythic'
]
let rarity = rarities[Math.floor(Math.random() * rarities.length)]
function generateRarity(length, times) {
let numbers = [];
for (i = 0; i < times; i++) {
let number = Math.floor(Math.random() * length)
numbers.push(number)
}
return numbers;
}
let indexArray = generateRarity(rarities.length, args)
let generatedRarities = [];
indexArray.forEach(index => generatedRarities.push(rarities[index]))
sentrarities = "#".join(generatedRarities)
await message.reply(sentrarities)

How to fix 'Cannot convert Array to Object[][]' error in Google Apps Script

I'm attempting to get a list of all groups and all members of a group to be posted to a spreadsheet titled 'allGroups'. However, whenever I try to print the Array to the sheet I'm getting the error that says I can't convert the Array to an Object.
I've tried setting the array to be different sizes, changing the range so that it's more specific, and changing the code so that the group name is posted first (clearing the Array) and then moving from there but it hasn't worked.
function listAllGroupsAndMembers() {
var ss = SpreadsheetApp.getActive();
var groupPageToken, groupPage;
var listArray = [];
var outputSheet = ss.getSheetByName('allGroups') || ss.insertSheet('allGroups', 1);
outputSheet.clear();
do {
groupPage = AdminDirectory.Groups.list({
domain: 'google.com',
maxResults: 100,
pageToken: groupPageToken
});
var groups = groupPage.groups; //Gets the list of groups and begins to iterate for each one
if (groups) {
for (var i = 0; i < groups.length; i++) {
var group = groups[i];
listArray.push([group.name]);
var membersPageToken, membersPage;
do {
membersPage = AdminDirectory.Members.list(group.email, {
maxReults: 100,
pageToken: membersPageToken});
var members = membersPage.members;
if (members) {
for (var u = 0; u < members.length; u++) {
var member = members[u];
listArray.push(member.email);
outputSheet.getRange(u+1, i+1, listArray.length, listArray[0].length).setValues(listArray);
}
listArray = [];
} membersPageToken = membersPage.nextPageToken;
} while (membersPageToken);
}
}
} while (groupPageToken);
try {
outputSheet = ss.getSheetByName('allGroups');
outputSheet.getDataRange();
} catch(err) {
outputSheet = ss.insertSheet('allGroups', 2);
}
}
Expected results would be that a list of groups would populate across row 1, and the list of member's emails would appear below each group. Currently once I get to
outputSheet.getRange(u+1, i+1, listArray.length, listArray[0].length).setValues(listArray);
it tells me that can't convert the Array to an Object and fails.
EDIT
I've managed to get it working thanks to AMolina, Ross, and Cooper. This is the code I've got now:
function listAllGroupsAndMembers() {
var ss = SpreadsheetApp.getActive();
var groupPageToken, groupPage;
var listArray = [];
var outputSheet = ss.getSheetByName('allGroups') || ss.insertSheet('allGroups', 1);
var p = 0;
outputSheet.clear();
do {
groupPage = AdminDirectory.Groups.list({
domain: 'google.com',
pageToken: groupPageToken
});
var groups = groupPage.groups; //Gets the list of groups and begins to iterate for each one
if (groups) {
for (var i = 0; i < groups.length; i++) {
var group = groups[i];
listArray.push([group.name]);
var membersPageToken, membersPage;
do {
membersPage = AdminDirectory.Members.list(group.email, {
maxReults: 100,
pageToken: membersPageToken});
var members = membersPage.members;
if (members) {
for (var u = 0; u < members.length; u++) {
var member = members[u];
listArray.push([member.email]);
}
if(membersPageToken != undefined) {
p = p + 200;
} else { p = 0; }
Logger.log(p);
outputSheet.getRange(p+1, i+1, listArray.length, listArray[0].length).setValues(listArray);
listArray = [];
} membersPageToken = membersPage.nextPageToken;
} while (membersPageToken);
}
}
} while (groupPageToken);
try {
outputSheet = ss.getSheetByName('allGroups');
outputSheet.getDataRange();
} catch(err) {
outputSheet = ss.insertSheet('allGroups', 2);
}
}
It also is able to handle when there's more than 200 members in a group.
Try this:
function listAllGroupsAndMembers() {
var ss = SpreadsheetApp.getActive();
var groupPageToken, groupPage;
var listArray = [];
var outputSheet = ss.getSheetByName('allGroups') || ss.insertSheet('allGroups', 1);
outputSheet.clear();
do {
groupPage = AdminDirectory.Groups.list({
domain: 'sbtagent197.eu',
maxResults: 100,
pageToken: groupPageToken
});
var groups = groupPage.groups; //Gets the list of groups and begins to iterate for each one
if (groups) {
for (var i = 0; i < groups.length; i++) {
var group = groups[i];
listArray.push([group.name]);
var membersPageToken, membersPage;
do {
membersPage = AdminDirectory.Members.list(group.email, {
maxReults: 100,
pageToken: membersPageToken});
var members = membersPage.members;
if (members) {
for (var u = 0; u < members.length; u++) {
var member = members[u];
listArray.push([member.email]);
}
// This is where I made the change, moving this line outside the inner loop.
outputSheet.getRange(1, i+1, listArray.length, listArray[0].length).setValues(listArray);
listArray = [];
} membersPageToken = membersPage.nextPageToken;
} while (membersPageToken);
}
}
} while (groupPageToken);
try {
outputSheet = ss.getSheetByName('allGroups');
outputSheet.getDataRange();
} catch(err) {
outputSheet = ss.insertSheet('allGroups', 2);
}
}
I modified the code you had by changing the location of the outputSheet.getRange(1, i+1, listArray.length, listArray[0].length).setValues(listArray); line, you were calling it several times during the loop, which was causing the title to appear many times. basically, you were writing the block of group_name -> members over and over, one row lower every time, so it looked like you were writing the title a bunch of times when it was the whole thing.
The edited code sets the values once when the array is complete, it will write the name of the group in the first row and the members in the rows below it. Moving forward I would suggest you consider #Cooper 's advice, using getValues() and setValues() can make working with sheets much easier.

How can I do to aggregate count function return a number not an array

I try to count number of each article but the result is not what I want
This is my code
var nameWebsites = await Article.distinct("website.name");
var idWebsites = await Article.distinct("website.id");
var numberArticle = [];
var result = [];
for(var i = 0; i < nameWebsites.length; i++) {
await Article.aggregate([
{ $match: {"website.id": idWebsites[i]}},
{ $count: "count"}
], function(err, result){
numberArticle.push(result);
});
}
for(var i = 0; i < nameWebsites.length; i++) {
result.push({"id":idWebsites[i], "name":nameWebsites[i], "number_article": numberArticle[i]});
}
And this is a part of result
{"data":[{"id":1,"name":"Dan tri","number_article":[{"count":52952}]},...]}
I want the result like:
{"data":[{"id":1,"name":"Dân trí","number_article":52952},...]}
Instead of grabbing the entire results of numberArticle[i], get the just count of the first object in the array.
for(var i = 0; i < nameWebsites.length; i++) {
result.push({
id: idWebsites[i],
name: nameWebsites[i],
number_article: numberArticle[i][0].count,
});
}
var objectArray = {"data":[{"id":1,"name":"Dân trí","number_article":52952}]}
Then you can use
objectArray.data.length

Adding Markers to Google map from json Array

This is my poor code
function loaddata() {
var url = "http://localhost/Geocording/api.php";
$.getJSON(url, function (data) {
var json = data
for (var i = 0, length = json.length; i < length; i++) {
var val = json[i],
var latLng = new google.maps.LatLng(val.lat, val.lng);
console.log(latLng)
}
});
}
Im trying to get details from my own api using json array.
but its not working.
{"location":[{"name":"Home 1","lat":"6.824367","lng":"80.034523","type":"1"},{"name":"Grid Tower 1","lat":"6.82371292","lng":"80.03451942","type":"1"},{"name":"Power Station A","lat":"6.82291793","lng":"80.03417451","type":"1"}],"success":1}
This is json response from my api.php
Try to make things clear first then apply it. First read JSON clearly then go on to apply it in your code. This is the working code.
function loaddata() {
var url = "http://localhost/Geocording/api.php";
$.getJSON(url, function (data) {
var json = data['location'];
for (var i = 0, length = json.length; i < length; i++) {
var val = json[i];
var latLng = new google.maps.LatLng(val['lat'], val['lng']);
console.log(latLng)
}
});
}
Hope this may help you!

Google script, empty array from fetched API

I'm trying to fetch my ETH balance and transactions from etherscan.io website and I'm trying to use the same code I used before for another website. But it seems returning me an empty array, and also the error "The coordinates or dimensions of the range are invalid."
This is the code:
function getTx() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
var url = 'http://api.etherscan.io/api?module=account&action=txlist&address=0x49E81AA0cFE7eeA9738430212DC6677acF2f01a1&sort=asc';
var json = UrlFetchApp.fetch(url).getContentText();
var data = JSON.parse(json);
var rows = [],
array;
for (i = 0; i < data.length; i++) {
array = data[i];
rows.push([array.timeStamp, array.from, array.to, array.value]);
}
Logger.log(rows)
askRange = sheet.getRange(3, 1, rows.length, 3);
askRange.setValues(rows);
}
The logged "rows" is empty, what am I doing wrong?
Thank you
How about a following modification?
Modification points :
There is data you want at data.result.
Number of columns of data is 4.
Modified script :
function getTx() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
var url = 'http://api.etherscan.io/api?module=account&action=txlist&address=0x49E81AA0cFE7eeA9738430212DC6677acF2f01a1&sort=asc';
var json = UrlFetchApp.fetch(url).getContentText();
var data = JSON.parse(json);
var rows = [],
array;
for (i = 0; i < data.result.length; i++) { // Modified
array = data.result[i];
rows.push([array.timeStamp, array.from, array.to, array.value]);
}
Logger.log(rows)
askRange = sheet.getRange(3, 1, rows.length, 4); // Modified
askRange.setValues(rows);
}
If I misunderstand your question, I'm sorry.

Resources