How is data stored in arrays from getValue - javascript

In Google Sheets looking as part of a script to store data in a range to an array then to check whether a certain column has an "Y" in so I can loop through and store these columns in new arrays.
I have the following code but am getting this error - "TypeError: Cannot read property "0.0" from undefined."
var data = sheet.getRange("A6:U37").getValues;
if (data[20][i]=="Y"){
(The if code is generating the error)
Believe I am misunderstanding how the range is stored in the array causing the error any advice?

In the first line of code you provided, you are referencing the function getValues rather than actually calling it. In order to do so, you just have to modify the code as follows:
var data = sheet.getRange("A6:U37").getValues();
if (data[20][i]=="Y"){
Next time you have issues similar to this one, you can consider using logging or other debugging techniques in order to debug your script.

Related

Trying to turn an array of entries into an object but doesn't work, why?

I'm trying to turn an array in which every element is an array containing the key, and the value(like entries), I'm trying to convert it back to an object element by the help of the method Object.fromEntries(array) but there seem to be a problem.
This is the error I get: TypeError: Object.fromEntries requires the first iterable parameter yields objects
Here's how I use the method:
const saved = JSON.parse(Object.fromEntries(localStorage.getItem(key)))
The local storage value it should retrieve:
[["$$typeof",null],["type",null],["key",null],["ref",null],["props",{"data":"a data containing collections of objects(fetched from an API)"}]
Since it might be helpful, what I'm trying to do is to store a react component(yes, I work on ReactJS) to local storage and get it back when necessary.
If you don't think that this portion of code is not the reason why this issue appears, please do let me know.

MongoDB weird behavior needs explanation

So yesterday I started messing around with MongoDB in Node and when it comes to retrieving data I encountered a weird practice.
You retrieve data from a collection that is nested within a database by calling.
data = client.db([dbname]).collection([collectionname]).find([searchcriteria])
and this returns what seems to be an object at least in the eyes of typeof
the sample code then uses the following lines to log it to the console:
function iterate(x){
console.log(x)
}
data.forEach(iterate)
The output is as expected in this case two objects with 2 pairs everything is fine so far.
I thought it is a bit unnecessary to have the iterate function so I changed that to just
console.log(data)
expecting the 2 objects in a array or nested in another object but what i get is this huge object with all kinds of different things in it EXCEPT the two objects that we saw before.
So now to my Question and what I need deeper explanation on:
why can i actually use .forEach() on this object I cannot recreate this on other objects.
and the second thing is why is console.log(data) giving me all this output that is hidden if I call it through .forEach()?
and is there any other way to quickly within one or 2 lines of code retrieve data from Mongo ?
this seems to be a very not useful way of doing things.
and how does this .forEach() thing on objects work I found a article here on stack however this was not very detailed and not very easy to understand.
The find function returns a cursor - this is the huge object that you are seeing. Checkout documentation for more details here: https://docs.mongodb.com/manual/reference/method/db.collection.find/#db.collection.find
The reason why you can call forEach on the returned object (=cursor), is because it is one of its methods. See https://docs.mongodb.com/manual/reference/method/cursor.forEach/#cursor.forEach
Overview of all cursor methods is here: https://docs.mongodb.com/manual/reference/method/js-cursor/
To get the array of data that you are looking for you need to use the toArray method, like so:
const data = client.db([dbname]).collection([collectionname]).find([searchcriteria]).toArray()

Get range based on indexOf

Im trying to access a specific cell, in a row that corresponds to an index. So for index 5, go to cel F6 and do stuff. I’am getting the following error:
TypeError: isInColumnid is not a function, it is number. (line 23, file "testing4")
This is my code:
var isInColumnid = columntosearchid.indexOf(id)
var valuestoreplace = isInColumnid.getRange('!I:O')
I think you can save yourself a good amount of hassle on this by using the
math.range(start, end [, includeEnd]) syntax.
You will be able to pass your variables appropriately while also saving lines of confusion.
My obvious mistake was trying to get a range from a number, or applying a method to a result I’ve already gotten. So thinking a bit further, it makes more sense to look for the cell in the respective sheet and telling .getRange the exact coordinates by using the existing index as below.
var valuestoreplace = sheet2.getRange(isInColumnid+1, 9)

Object in javascript stuck on last line of csv file

Im currently trying to build a choropleth on the map of Puerto Rico using D3. Using Scott Murray's Example on Choropleths, I'm trying to bind data to each municipality of Puerto Rico. I have a placeholder empty object to hold the data being fed from the CSV like so:
var properties = {};
Then, I proceed to read the CSV file by row. I assign the corresponding values to some variables like so:
properties.dataID = parseFloat(data[i].id);
properties.dataMunic_Total = parseFloat(data[i].municipio_total);
//etc.
All fine and dandy. I console.log to check whether or not the data was stored correctly:
console.log(properties.dataID);
//Displays 1, which is correct.
However, when I try to access the whole object:
console.log(properties);
it only displays the last row of the CSV file. I ran that last console.log() statement inside the first for loop, immediately after assigning the data to the object's properties, and every time the loop iterates through the console.log(), it ONLY displays the last line of the CSV file.
When I try to assign the object properties to my map's objects (municipalities), all that it ever assigns is that last line of the CSV file. So I tried setting them up individually, seeing that seems to have worked. However, JavaScript complains that the property does not exist in the object:
obj.geometries[j].properties.year[properties.dataYear - 2000].id = properties.dataID;
Uncaught TypeError: Cannot read property 'id' of undefined
I tried initializing it as if it were a new variable:
var obj.geometries[j].properties.year[properties.dataYear - 2000].id = properties.dataID;
but then I got this back on the console:
Uncaught SyntaxError: Unexpected identifier
Aside from the syntax error, I think that this is mainly due to the fact that I appended an array to each municipality so I could hold different sets of data per year... but I don't understand why JavaScript behaves this way.
My question is: why does my object behave this way? Is there something wrong with d3.csv? Am I doing something wrong?
If you want to store several properties, you need to use an array (i.e. a list). In the code you are using, you are only creating a single variable properties at a time and not saving the references to the ones you have created previously. That is, in each iteration of the loop, you are creating a new object, but losing the old one.
If you declare properties as an array and then append new property objects in the loop, you can reference them later and use them to draw the map. The code would look something like this.
var properties = [];
for(var i = 0; i < data.length; i++) {
var property = {};
property.dataID = parseFloat(data[i].id);
property.dataMunic_Total = parseFloat(data[i].municipio_total);
// ...
properties.push(property);
}
After setting up the data like this, you should be able to proceed as described in the example.

Undefined values in Javascript object

So I am trying to store an array of objects into localStorage, as follows:-
EDIT: The following is part of a function that is called in a loop.
c = [{"name":nameDOM.value,"add":+addDOM.value,"town":townDOM.value,"post":postalDOM.value,"mob":mobDOM.value}];
cData = cData.concat(c);
localStorage.setItem('cData', cData);
However, after a page refresh, when I try to access data from the objects, it is apparently undefined. Accessing data from the objects is fine before a refresh.
I am accessing the data in the following manner:-
//Table code omitted.
var text = document.createTextNode(""+cData[i].name+", "+cData[i].add+", "+cData[i].town+", "+cData[i].post+", "+cData[i].mob+"");
I have been trying to debug the problem using Chromes Javascript tools, as well as inserting alerts into various places to monitor the state of the variables; still undefined.
You've made an oopsies. Try:
c = [{"name":nameDOM.value,"add":+addDOM.value,"town":townDOM.value,"post":postalDOM.value,"mob":mobDOM.value}];
cData = cData.concat(c);
localStorage.setItem('cData', JSON.stringify(cData));
They difference being that you are turning your array of objects into a json string that can be parsed later by your code using:
eval(localStorage.getItem('cData'));

Categories

Resources