Javascript storing multiple fields in an array - javascript

I was wondering if it's possible to store multiple different fields in a dynamic array using Javascript.
In Informix it is called a dynamic array of records and it is accomplished like this
# define array of record
la_data dynamic array of record
var_idno integer,
var_desc char(30)
end record
# populate array of record
for lv_cnt = 1 to 10
let la_data[lv_cnt].var_idno = lv_cnt
let la_data[lv_cnt].var_desc = "dummy data"
end for
# use stored data
display la_data[5].var_idno # will output 5
display la_data[5].var_desc # will output dummy data
How would I do something similar (or completely different) using Javascript

// define array of record
var la_data = [];
// populate array of record
for (var lv_cnt = 1; lv_cnt <= 10; lv_cnt++) {
// This initializes an object we can put your properties on
la_data[lv_cnt] = {};
la_data[lv_cnt]['var_idno'] = lv_cnt;
la_data[lv_cnt]['var_desc'] = "dummy data";
}
// use stored data
console.log(la_data[5].var_idno) // will output 5
console.log(la_data[5].var_desc) // will output dummy data
Fiddle: http://jsfiddle.net/xxqkfuot/
As you can see in other answers there are simpler ways to do this but I was attempting to keep the code as similar as possible so you could see the connection between the lines.

I suppose you could create sometihng like a dynamic array in javascript, but the simplest and most idiomatic thing to do with pure javascript would be to use a list:
var list = [];
for (i = 0; i < 10; i++)
list.push({var_idno: i, var_desc: 'Dummy data'});

JavaScript is loosely typed so this is actually too easy to do.
var one = 1;//int
var two = "String";//String
var three = {
"name": "Foo",
"address": "bar"
};//Object
var array = [one, two, three];
console.log(array[0]);//1
console.log(array[1]);//String
console.log(array[1]);//[Object]

Related

How do I insert an array into a Google Doc using data from Google Sheets?

I am trying to pull a range of names from a Google sheet and place it into a Google Doc.In the spreadsheet, the last names("lastNames") come before the first names ("firstNames"), and both are in separate columns. I am trying to place the first and last names together into my doc with the first names first.
I used a for loop to put the first and last names together into an array ("fullNames"), and that part works just fine. When I used Logger.log, all the first names and last names are together in an array, with each full name separated by a common, just the way I wanted them to be.
What I can't figure out how to do is actually insert this new array into the body of the document. I am using the appendTable method, but every time I try to I get the following error: "The parameters (number[]) don't match the method signature for DocumentApp.Body.appendTable."
What changes do I have to make to my code to actually place my new array into my google doc?
function namePusher() {
var ss = SpreadsheetApp.openById("1CHvnejDrrb9W5txeXVMXxBoVjLpvWSi40ehZkGZYjaY");
var lastNames = ss.getSheetByName("Campbell").getRange(2, 2, 18).getValues();
var firstNames = ss.getSheetByName("Campbell").getRange(2, 3, 18).getValues();
//Logger.log(firstNames);
var fullNames = [];
for(var i = 0; i < firstNames.length; i++){
var nameConcat = firstNames[i] + " " + lastNames[i]
fullNames.push(nameConcat);
}
//Logger.log(fullNames);
var doc = DocumentApp.getActiveDocument().getBody();
doc.appendTable(fullNames);
}
Modification points:
I think that there 2 reasons in your issue.
Values retrieved by getValues() is 2 dimensional array.
data of appendTable(data) is required to be 2 dimensional array.
In your script, fullNames is 1 dimensional array. By this, such error occurs.
In your script, the values are retrieved 2 columns using 2 getValues(). In this case, the cost will become a bit high. You can retrieve the values using one getValues().
When these points are reflected to your script, it becomes as follows.
Modified script:
function namePusher() {
var ss = SpreadsheetApp.openById("1CHvnejDrrb9W5txeXVMXxBoVjLpvWSi40ehZkGZYjaY");
var values = ss.getSheetByName("Campbell").getRange("B2:C19").getValues(); // Modified
var fullNames = [];
for(var i = 0; i < values.length; i++){ // Modified
var nameConcat = [values[i][1] + " " + values[i][0]]; // Modified
fullNames.push(nameConcat);
}
var doc = DocumentApp.getActiveDocument().getBody();
doc.appendTable(fullNames);
}
References:
getValues()
appendTable(cells)
One simple way to fix your code is by replacing
fullNames.push(nameConcat);
by
fullNames.push([nameConcat]);
The problem with your script is that fullNames is an Array of strings but your should pass an Array of Arrays of strings (or objects that might be coerced to strings).
Basic demo
var data = [
['A','B','C'],
[1, 'Apple','Red'],
[2, 'Banana','Yellow']
];
function myFunction() {
const doc = DocumentApp.getActiveDocument();
const body = doc.getBody();
body.appendTable(data);
}
As mentioned on Tanaike's answer there are other "improvement opportunities"
Reduce the number of calls to the Google Apps Script Classes and Methods
Use better ways to manage Arrays and to concatenate strings.

Appending an array with multiple arrays in google script

I have an array where I send a set of values after an operation on a spreadsheet followed by taking the average.
Now I want to return each row also along with the above data.
I thought of using two-dimensional arrays.
But I have less clarity in implementing this.
for (var i = 0; i < spreadsheetRows.length; i++)
{
//operations done and variables updated
variable1=
variable2=
variablen=
}
var sendArray = [];
sendArray.push(variable1);
sendArray.push(variable2);
sendArray.push(variable3);
sendArray.push(variable4);
return sendArray;
Now i want to send the array rowFirst & rowSecond also
for (var i = 0; i < spreadsheetRows.length; i++)
{
//first row of spreadsheet
rowFirst=[]; //data of first row
rowSecond=[]; //data of second row
//operations done and variables updated
variable1=
variable2=
variablen=
}
var sendArray = [];
sendArray.push(variable1);
sendArray.push(variable2);
sendArray.push(variable3);
sendArray.push(variable4);
sendArray.push(rowFirst); // stuck here <---
sendArray.push(rowSecond);// stuck here <----
return sendArray;
How to send the array with these two data( ie rowFirst and rowSecond) . Please guide me.
Output Expected
sendArray=[
var1,
var2,
var3,
varn,
rowFirst=[num1, num2, num3,...numn]
rowSeocnd=[num1, num2, num3,...numn]
]
To answer your immediate question, you can push an array into another array by using square brackets in push.
sendArray.push([rowFirst]);
sendArray.push([rowSecond]);
Based on your comment, you may want to use an Object, not an Array (here's a helpful article on the differences). So, think through why you'd want four variables not associated with anything. Can those be grouped or keyed somehow? There are a number of ways to do this and a simple method is to use dot notation to pair a variable or a data set to an object key.
// declare the object and each array
var sendObject = {}
// from your code...
for (var i = 0; i < spreadsheetRows.length; i++)
{
//operations done and variables updated
variable1=
variable2=
var rowFirst = [variable1, variable2, ...]
}
// Create the key in the Object and assign the array
sendObject.rowFirst = rowFirst;
The output would be:
sendObject = {
"rowFirst": [variable1, variable2, ...]
}

how to make index dynamic for json objects

i'm tring to dynamically display eveyrthing that comes back from the server, however to get it displaying i have to explicitly write in the index of the object i'm trying to access, how can i make this dynamic so it goes through them all?
i am Using AngularJS, Express, and Mongoose.
here is the code snippet where the index i want to change on its own located.
app.controller('MainController', ['$scope', 'whipmeet', function($scope, whipmeet) {
whipmeet.getWhipmeets(function(JSON){
$scope.meetinfo = JSON;
$scope.meetparts {
name = JSON.data["0"].name,
location = JSON.data["0"].location,
car = JSON.data["0"].car,
date = JSON.data["0"].date,
time = JSON.data["0"].time,
type = JSON.data["0"].type,
stock = JSON.data["0"].stock
};
what i'm trying to achieve is that the ["0"] index change dynamically to get all the indexes of the objects so i can get those zeroes to go 1 to 2 to 3 and so on untill there are no more
There are few options.
From my understanding, you are trying to iterate through the JSON object that is returned to you.
You can either use:
var meetpartList = [];
JSON.foreach(function(d) {
// do your parsing here
newObject = {};
newObject.name = d.name;
// etc..
meetpartList.append(newObject);
});
or you can use:
for (int i = 0; i < numberOfIndicesInJson; i++) {
// get values using JSON[i + ""].key;
}
to do something similar as above to create a list of meets.
Then you can use that list of meets to render into your view using ng-repeat, which I hope is the solution you're looking for?

JavaScript Array with multiple items

I am trying to create a array with multiple fields in it.
For Example:
var person1 = {firstname:"Bob", lastname:"Smith", middlename:"happy"};
The problem I have is that I have 5000 variables I want to create so it would become:
var person1 = {firstname:"Bob", lastname:"Smith", middlename:"happy"};
var person2 = {firstname:"John", lastname:"Jones", middlename:"Long"};
..
var person5000 = {firstname:"Jim", lastname:"Cook", middlename:"Shorty"};
I think it would be silly to have 5000 lines of code to declare the variables.
So I want to be able to declare the variables on page load and then later assign the values to each.
I was trying to do this using the following code but I am guessing I am doing something wrong.
(I am loading some dummy data into the variables for testing)
<!DOCTYPE html>
<html>
<body>
<script>
var person = new Array (firstName:"", lastName:"", middleName:"");
for (var i = 0; i < 5000; ++i) {
person[i] = {firstName:"First"+i, lastName:"Last"+i, middlename:"Middle"+i};
}
alert(person1["firstName"]); // should alert First1
alert(person6["lastname"]); // should alert Last6
</script>
</body>
</html>
I was hoping to later in my code set the value using:
(I am pretty sure this code should work, but can't test it since I can't declare the variables correctly)
person1[firstname] = "Terry"; // should replace First1 with Terry
And then to receive a value using:
alert(person1[firstname]); // should alert Terry since it was changed
Anyone know what is wrong with my code since it's not returning the value ?
I am guessing I am declaring the variables wrong? If so how should I declare them ?
You appear to be confused about the difference between arrays and objects in Javascript. Arrays have numeric indexes, objects have named properties. So the initialization
new Array(firstName:"", lastName:"", middleName:"");
makes no sense. Not to mention, it's not valid Javascript syntax; property: value pairs can only be used in object literals, not in argument lists. If you use new Array(...), the argument should either be a single number, which is the size of the array to allocate, or a list of initial array element (with no property: prefixes. But the preferred way to create a new array is simply with the [] literal for an empty array; it will grow as necessary when you assign to it.
When you create an array, you don't get separate variables for each element. You access them using array[n] notation.
// Create an empty array
var person = [];
// Fill up the array
for (var i = 0; i < 5000; ++i) {
person[i] = {firstName:"First"+i, lastName:"Last"+i, middlename:"Middle"+i};
}
// Access elements
alert(person[1].firstName);
alert(person[6].middleName);
// Change elements
person[1].firstName = "Terry";
I believe this should work as you intended:
var person = new Array();
for (var i = 0; i < 5000; ++i) {
person[i] = {firstName:"First"+i, lastName:"Last"+i, middleName:"Middle"+i};
}
alert(person[1]["firstName"]);
alert(person[6]["lastName"]);
As pointed out by others, the person array is filled with objects, not arrays. You can use either property or associative array syntax with them.

Cannot access second field in a 2 dimension array in javascript

I have a 2 dimension array defined as
var thischart = [[],[]];
and the array contains the following data created programatically:
1,0,2,0,3,0,4,0,5,0,6,0,7,0,8,0,9,0,10,0,11,0,12,0,13,24,14,0,15,0,16,0,17,0,18,0,19,0,20,0,21,0,22,0,23,0,24,0
I cannot get the single value of the second field in the particular array cell. For example, if I use the following command to get the value:
alert("thischart[i,1]=" + thischart[0, 1]);
I get the following answer:
thischart[i,1]=2,0
I tried using the second dimension to access the data as
thischart[0][1]);
but it gives me an error message:
I just want to get the second single value in the array such as for array cell 13 I want the value 24 from above. Does anyone have an answer on how to access this array?
I populated the array as follows and then updated it thru program logic:
$hours = [];
for($i = 0; $i< 24; $i++){
$hours[$i] = [];
$hours[$i][0] = ($i + 1);
$hours[$i][1] = "0";
}
And the answer to this question is below:
for(var i in thischart){
var tc = thischart[i];
myvalue = tc[1]); // this is the value I want
}
Thanks to everyone who responded.
For all of them like this:
for(var i in thischart){
var tc = thischart[i];
for(var n in tc){
// n is internal index
// tc[n] is internal value
}
}
For a single value from the first internal Array, the second value:
thischart[0][1];
Why don't you use the console to see what's the return of
thischart[0];
Because it should contain an array. If it does, then
thischart[0][1];
is perfectly valid syntax. And if it doesn't, then
thischart[0,1]
means nothing whatsoever.
Do something like this:
var items = [[1,2],[3,4],[5,6]];
alert(items[0][0]); // 1
do you mean something like this:...
http://jsfiddle.net/DSrcz/1/
var arr = [1,0,0,0,0,0,0,0,0,0,0,0,0,24,0,0,0,0];
arr[33]=1000;
alert(arr[13]);
alert(arr[33]);

Categories