Formatting to Export from Sheets to Firebase - javascript

I'm working on an app/sheets combination scoring system for a tournament. The current data in the Firebase database is stored under a tag like so: tag:"[\"Test\",-1,12,3]"
The data is in the form of a list containing a single string and 3 numbers. Each index in the list will be stored in consecutive cells so referencing the data is easy. The difficulty I am having is formatting the data from the sheet to write it to the database in the same format.
Using JSON.stringify doesn't quite give me what I'm looking for:
var range = sheet.getRange(22,24,4,1);
var data = JSON.stringify(range.getValues());
result:
tag:"[[\"Test1\"],[70],[0],[18]]"
This is not quite the same as the rest of the data as I'm turning the entire range to a string by using stringify, but I don't know of a way to format the data to be stored as [string, int,int,int]. I am new to app scripts and java (hence my lack of knowledge of functions) and was hoping somebody knows of another way to write the range of cells to match the data stored in the database.

First thing, Google Apps Scripts uses JavaScript, not Java.
Second thing getValues() returns a Array of Arrays where each inner Array has the values of a row from the corresponding range. In order to get what you are looking for you have to flatten the result of getValues(). One way to do this is this:
var range = sheet.getRange(22,24,4,1);
var data = JSON.stringify(range.getValues().map([value] => value));
var values = [["Test1"],[70],[0],[18]];
var data = JSON.stringify(values.map(([value]) => value));
console.info(data)

Related

scrape Highcharts series.data categories?

I want to export chart data from a website.
Using console.log(Highcharts.charts[0].series[0].data) I can see the data I need.
I want the values stored under Highcharts.charts[0].series[0].data[n].category for n in [0, 1, ..., N_data_points-1] (These values are the time-stamps of the data points in the plot.)
When I try to use JSON.stringify(Highcharts.charts[0].series[0].data) to write the whole data attribute I get Uncaught TypeError: Converting circular structure to JSON.
How can I get that data[n].category values for all n data points?
Note that the x axis data can be obtained straightforwardly via Highcharts.charts[0].series[0].processedXData, but these are not the dates, just consecutive integers.
Also, I don't necessarily need to do this via console. If it's possible to get the data via, say, a Python script, that would do as well.
You can adapt the python/selenium script here.
Most of the stuff remains as is, except for obvious changes (change the url, etc).
You can get the category data of each data point with:
dates = []
for i in range(len(values)):
date = driver.execute_script('return Highcharts.charts[0].series[0].data[{}].category'.format(i))
dates.append(date[0])
EDIT: as pointed out in a comment, you can get the category data without a for loop using:
categories = driver.execute_script('return Highcharts.charts[0].userOptions.xAxis[0].categories')

Firebase javascript Admin SDK: length of the loaded array is incorrect

I have following data in my firebase realtime database.
I load this data from javascript admin SDK (nodejs).
firebaseAdmin.database().ref('db/path').on('value', snapshot => {
let data = snapshot.val();
});
Above data is loaded as an array and the length of the array is incorrect. Following is a visualization of the loaded data.
It can be seen that array length is shown as 5, even though there are only 4 items in the DB. The element in the zero'th index of the array is null.
What is the reason for this?
The length of a JavaScript array is always 1 + the max index in the array. In your case, it's 1 + 4 = 5. Empty elements count toward the size. This is true for a vast majority of programming languages out there.
Consider starting the array index in your database at 0 if you want to avoid confusion. A vast majority of programming languages also assume arrays are zero-indexed like this.

How do you access multi-dimensional arrays of objects in JavaScript?

I need to access JavaScript objects stored in a multi-dimensional array. The data is being exported by a WordPress plug-in. Note, I cannot change the code to use a single array.
There are two arrays named "employees". Is this array format compatible with JavaScript? The JSON export was intended for PHP processing.
(Note, The code below is a simplified model to illustrate the issue).
var data = '{"employees":[{"firstName":"John0"}, {"firstName":"Anna0"},{"firstName":"Peter0"}],"employees":[{"firstName":"John1"}, {"firstName":"Anna1"},{"firstName":"Peter1"}]};';
var json = JSON.parse(data);
document.querySelector('#test').innerHTML = json.employees[2].firstName;
Here it is on JSFiddle:
https://jsfiddle.net/2524fhf4/11/
How for example, would one access the value "Peter0" in the first array? In a single array, it would be accessed like this:
var result = json.employees[2].firstName;
It appears to me that in this format it is only possible to access the last array.
It appears to me that in this format it is only possible to access the
last array.
Because when your object literal has two (or more) keys of the same name, last one will override the rest of them.
Check this demo
var data = '{"employees":[{"firstName":"John0"}, {"firstName":"Anna0"},{"firstName":"Peter0"}],"employees":[{"firstName":"John1"}, {"firstName":"Anna1"},{"firstName":"Peter1"}]}';
console.log(JSON.parse(data)); //it will only display first one
In the above example, you can see that there is only one key of the data

Get Data from Text File to Multidimensional Array Javascript

I have a little bit of an issue with a JavaScript function that needs to read data from a TextFile (something JS is already limited with) and then process tha TextFile data into a MultiDimensional Array (another thing that JS doesn't nativelly suport).
With that in mind, I have a text file in this format:
1, Name, Data, Serial
2, Name, Data, Serial
3, Name, Data, Serial
And so on.
So, the objective is to get that same data and put it, like that, into an array.
I suppose that, from what I've been reading, I need an Array of an Array, segmenting the first one by lines [/n] and the second one by commas [,]. However, given the "by-default" limitations, I'm very confused at this point. I do suppose I need jQuery, however.
I tried this:
var fs = require('fs');
var array = fs.readFileSync('file.txt').toString().split("\n");
for(i in array) {
var array = fs.readFileSync('file.txt').toString().split(",");
for(f in array) {
}
}
With little success, because then I don't really know how to store it, the objective being a Multidimensional Array that Replicates the Format of the text file, so latter it could be used to search by index or instance following an user input to get results.
I really appreciate any help.
At first glance it seems like you are trying to read in a CSV file. If that is indeed the case I recommend node-csv:
http://www.adaltas.com/projects/node-csv/
https://github.com/wdavidw/node-csv
This helped me reading file to JavaScript, however this example converts retrieved data to JSON. Just looking at the format of your text file, I would assume a JSON string or Javascript object would work with your data.
Example convert to JSON
With JSON and JS objects, instead of referencing a array indexes eg. array[i][x]. you would replace [x] with .propertyName
data = {
"id": 1,
"name": "Fred"
};
//access data like this
data[i].name //will return "Fred" as i =0
to create JS object, just initialize array properties without the ""(quotation marks). accessing JS and JSON properties are done in the same way, main advantage over a multidimensional array is that you can reference an actual property name, as opposed to indexes.

Creating a better JSON format

I am returning a query object from Coldfusion as a JSON string which I then parse into JSON in Javascript. It has a bit of a strange format when I finally log it though.
I am faced with two problems. First, I do not know how to access the lowest element (i.e Arthur Weasley) as I cannot use a number in my selector (response.DATA[0].0 doesn't work because the lowest field name is a number). Second, is there any way to assign the values in the columns section to the fields that are numbered 1, 2 and 3?
What I'm really asking is how do I select my lowest level of data? If that can't be done because of the numbers for field names, how do I change the names to something more fitting?
My data logged:
First entry of first entry of DATA = response.DATA[0][0]
So
name = reponse.DATA[0][0];
trainsThing = response.DATA[0][1];

Categories

Resources