I'm not sure why this isn't working so if anyone can help that would be great. I have nested functions and I wand to push the value returned by the firebase query and re use it in another firebase query, and then again, in a loop. Its essentially a poor man's infinite scroll. Nonetheless, I cannot get the value of the "arr" variable into the "numWanted" array outside so I can use it again in the next loop. What can I do to achieve the desired result?
Also, I have have beed trying to make the inner variables global, and push them out to another variable but that doesn't seem to work. Possible that I am just doing it wrong?
Thanks in advance..
$scope.loadMoreData = function() {
var numWanted = [];
console.log(numWanted);
firebase
.database()
.ref('products')
.orderByChild('rank')
.startAt(0)
.endAt(numWanted)
.limitToLast(3)
.once('value', function(products) {
products.forEach(function(product) {
var product = {
rank: product.val().rank
};
arr = product.rank;
});
numWanted.push(arr);
console.log(numWanted);
});
};
P.S. I realize this code doesn't actually work as you cannot use an array in a firebase query. My plan is to extract the number I need once the array has been populated.
You have a conflict with your parameter named product and a local variable named product. You need to rename one of those.
Related
I'm making a script to loop in a Google Drive folder and noticed I don't know what's the best way to loop over iterators (specifically FolderIterator and FileIterator).
My first approach
const drive_id = '__________';
let base_folder = DriveApp.getFolderById(drive_id),
sub_folders = base_folder.getFolders();
Logger.log(base_folder.getFolders());
for(let sub_folder of sub_folders)
{
Logger.log(sub_folder);
}
outputs Error TypeError: sub_folders is not iterable.
Secondly I tried with while loops and checks on hasNext(), but I didn't find them beautifyl enough. I'm currently set with this for loop, that works and is clean enough but still looks a bit hacky.
/*...*/
for(let sub_folders = base_folder.getFolders(); sub_folders.hasNext();)
{
let sub_folder = sub_folders.next();
Logger.log(sub_folder);
}
Also notice how I couldn't declare sub_folder within the loop itself. So, what's the proper way of doing it?
Also, what if I wanted to use a map or filter on the sub_folders instead?
Note: this question is probably of broader scope than google-script, but I couldn't find the right terminology to ask the question differently so I preferred to stick to the particular case I found.
What's the proper way of looping a FolderIterator or FileIterator?
The proper way of doing it by using a while loop.
The reason for that has to do with the hasNext() function which returns a Boolean (true or false) and the only loop that natively works with booleans is the while loop.
Also, what if I wanted to use a map or filter on the sub_folders instead?
In your code sub_folder is an object of type Folder. Unfortunately, you can only retrieve the folders one by one within the while loop by using next() so you can't directly apply map or filter on the FolderIterator.
Instead, you can create an array of folders by pushing each folder to an array (within the while loop) and then use map.
Example:
This script finds all the folders and store them in an array and then uses map to get the name of each sub folder:
function myFunction() {
const base_folder = DriveApp.getFolderById('folder_id');
const sub_folders = base_folder.getFolders();
const folders = [];
while (sub_folders.hasNext()){
let folder = sub_folders.next()
folders.push(folder);
}
const folder_names = folders.map(f=>f.getName());
console.log(folder_names);
}
Here is a list of all the available methods you can apply to each element of the folders array: Class Folder
I have a quick question which I seem to be tripped up on.
I have a data structure like so:
data: {
accounts: [{
info: false
}]
}
Is there a "fancy" React way for me to get the value of the boolean associated with the info key?
I can of course retrieve the value with using map or find, but it always ends up being somewhat convoluted or involved code.
If I do something like
const { accounts } = data;
const customer = accounts.map(a => a.info);
The value for customer always ends up coming back as [false] instead of just false, which is really confusing me, because I am not sure why it would come back inside of an array, where it is not an array to begin with, and it is being mapped out of an array (accounts).
I had the same result when using forEach and find.
Is there something I'm missing? There has to be a quick Reactive one-liner to get the boolean value I'm looking for, and set it to a variable.
Anyone...?
data.accounts[0].info
or
Using underscore.js
_.first(data.accounts).info
I'm trying to call a REST API using for loop and store the output to an array. But the output shows in different arrays for each and every rest API call instead of everything in one array
for each (name in car.cars){
for(i=0; i<count;i++){
var arr = [];
var newid = car.cars[i].name;
var url = "myhost"
var method = "GET"
var response = "output from REST call"
arr.push(response)
}
}
But the output shows in different arrays for each and every rest API call instead of everything in one array
Where is "the output" there's nothing in your code.
Your Problem is that you're declaring the var arr = []; inside your for loop.
Initialize the array before the loop starts and just add your responses to that array.
Instead your creating a new array for each iteration of for(i=0; i<count;i++)
Take a step back and look at your code again. Where are you declaring your array? Inside the loop.
Next, ask yourself; what is the scope of that array? Only within the loop. Even if just in the outer loop, it won't stick around because as soon as that loop finishes, the array disappears.
Create the array and use it from outside the loops (both of them).
Further reading: Declaring variables inside or outside of a loop
UPDATE 4/30/2019: Thanks to #AuxTaco, I crossed out my inaccurate description of scope in JS. Please see the links in his comment for more reading on this!
I'm creating a game bot on telegram using node js.
Currently I'm facing a problem on shared variable (module.exports). I'm storing some of the data on the variable. And the problem is, the shared variable index always change. For example, please refer to my code below
var sharedVar = [];
createNewRoom = function(res) {
var index = sharedVar.length;
sharedVar.push({ groupId : res.chat.id }); // every time this function is invoked, it will create a new array inside sharedVar object
//Here comes the problem, it's about the index,
//because I'm using sharedVar to store arrays, then it will become a problem,
//if one array is deleted (the index will change)
var groupId = sharedVar[index].groupId; // it runs OK, if the structure of array doesn't change, but the structure of array change, the index will be a wrong number
}
As you can see, i got callGameData function, when i call it, it will show the last value of sharedVar, it's supposed to show the current room values / data.
As i mention on the code above, it's all about the dynamic array in the sharedVar object, the index will change dynamically
Any thoughts to tackle this kind of issue? I was thinking about using a new sharedVar object everytime the createNewRoom function is invoked, but the thing is, i have to use sharedVar in many different function, and i still can't figure it out on using that method.
EDIT
This is the second method
var gameData = undefined;
createNewRoom = function() {
this.gameData = new myConstructor([]); // it will instantiate a new object for each new room
}
myConstructor = function(data) {
var _data = data;
this.object = function() {
return _data;
}
}
callGameData = function() {
console.log(gameData);
}
An array is fundamentally the wrong data type to use if you want to keep indices the same even in the face of removing entries.
A better method is to use properties of an object. For example:
var roomCache = { nextId: 1 };
createNewRoom = function(res) {
roomCache[roomCache.nextId++] = {groupId: res.chat.id}; // Add a new object to the cache and increment the next ID
}
After adding two elements, you'll have the rooms in roomCache[1] and roomCache[2] - if you want to start at zero just change the original value of nextId. You can delete elements in this object and it won't shift any keys for any other objects - just use delete roomCache[1] for example to get rid of that entry.
This assumes there isn't a better ID out there to use for the cache - if, for example, it made more sense to lookup by res.chat.id you could certainly use that as the key into roomCache rather than an auto-incrementing number. Here's how it would look like to cache the values by the group ID instead:
var roomCache = { };
createNewRoom = function(res) {
roomCache[res.chat.id] = {groupId: res.chat.id}; // Assumes res.chat.id is not a duplicate of an already cached obhect
}
Now you could just look up by group ID in the cache.
Yes, it's definitely a problem cause you are not keeping track of the index in a logical way, you are relying on position on the array which it changes, you need something that doesn't change over time to keep consistency and supports deletition of the element without affecting the rest of the elements. You could use mongo to store the generated rooms by id or maybe redis or some kind of key value pair database to store that kind of information.
Here's a quite simple question but I have not been able to find an answer anywhere about this, so hopefully I can get the answer here.
I want to iterate through the keys in my database using:
for (var key in X) {
//X is the main object I need
}
However, in order to do this I need the actual object of the database, not the reference to the database. Because when I iterate over the reference I get a lot of nonsense properties. So how do I get the object containing all the keys that I add personally? Hopefully my question makes sense.
This can be done this way:
var value;
myDataRef.on('value', function(snapshot) {
value = snapshot.val();
})