How can I loop through creating Objects? - javascript

Below is what the code looks like right now, with less rows and less properties.
var row1 = new Object();
var row2 = new Object();
var row3 = new Object();
var row4 = new Object();
var row5 = new Object();
var row6 = new Object();
var row7 = new Object();
row1.name = "Hello World!";
alert (row1.name);
This code below doesn't work as intended because row isn't primitive, but I need to do something like this because I have a billion row variables.
var row = [];
var row1 = [];
var row2 = [];
var row3 = [];
row.push(1);
row[1].name = "Hello World";
alert(row[1].name);
How can I do this, if at all possible?

var rows = [];
for(var i = 0; i < 7; i++)
{
rows.push(new Object());
}
rows[0].name = "Hello World!";
alert(rows[0].name);

You can create custom complex objects in javascript like this:
//complex object
ComplexObj = function(){
var self = {
'prop1': 'value1',
'prop2': 'value2',
'prop3': {
'subprop1': 'subvalue1',
'subprop2': 'subvalue2'
},
'prop4': [
1, 2, 3, 4
]
};
return self;
};
//code that creates instances of the complex object
var rows = [];
var newObj1 = new ComplexObj();
newObj1.prop1 = 'newvalue1';
var newObj2 = new ComplexObj();
newObj2.prop3.subprop2 = 'newsubvalue2';
rows.push(newObj1);
rows.push(newObj2);
for (var i = 0; i < rows.length; i++){
alert('row' + i + ': prop1=' + rows[i].prop1 + ' subprop2=' + rows[i].prop3.subprop2);
}
You can view the demo here. Notice that I update newObj1.prop1 and newObj2.prop3.subprop2 to show that newObj1 and newObj2 are different instances of ComplexObj.
http://jsfiddle.net/p5evg/1/

Related

How to use the result of an IF statement as a variable

I have a code as follows:
function DetailFacture2() {
var ss = SpreadsheetApp.getActive();
var DetailDEVIS = SpreadsheetApp.setActiveSheet(ss.getSheetByName('DetailDEVIS'));
var FACTUREDevis = SpreadsheetApp.setActiveSheet(ss.getSheetByName('FACTUREDevis'));
var DetailFactureDevis = SpreadsheetApp.setActiveSheet(ss.getSheetByName('DetailFactureDevis'));
var lastrowpaste = FACTUREDevis.getLastRow();
var numrow = FACTUREDevis.getRange(lastrowpaste,13).getValue()
var lastrowpaste2 = DetailFactureDevis.getLastRow() - numrow +2;
var data = DetailDEVIS.getDataRange().getValues();
var DetailD = FACTUREDevis.getRange(lastrowpaste,2).getValue();
for(var i = 0; i<data.length;i++){
if(data[i][1] == DetailD){ //[1] because column B
var firstrowcopy = i+1;
Logger.log(firstrowcopy)
return (firstrowcopy)
}
}
};
It does return the correct value, but how do you use "firstrowcopy" as a fixed var?
I would like to use as follows:
function DetailFacture2() {
var ss = SpreadsheetApp.getActive();
var DetailDEVIS = SpreadsheetApp.setActiveSheet(ss.getSheetByName('DetailDEVIS'));
var FACTUREDevis = SpreadsheetApp.setActiveSheet(ss.getSheetByName('FACTUREDevis'));
var DetailFactureDevis = SpreadsheetApp.setActiveSheet(ss.getSheetByName('DetailFactureDevis'));
var lastrowpaste = FACTUREDevis.getLastRow();
var numrow = FACTUREDevis.getRange(lastrowpaste,13).getValue()
var lastrowpaste2 = DetailFactureDevis.getLastRow() - numrow +2;
var data = DetailDEVIS.getDataRange().getValues();
var DetailD = FACTUREDevis.getRange(lastrowpaste,2).getValue();
for(var i = 0; i<data.length;i++){
if(data[i][1] == DetailD){ //[1] because column B
var firstrowcopy = i+1;
var source = DetailDEVIS.getRange(firstrowcopy,1,numrow-1);
var destination = DetailFactureDevis.getRange(lastrowpaste2,3);
source.copyTo(destination);
}
}
};
But, as one would expect, it cannot work as it loops...
Not sure if I understand your question too. The code doesn't look well. Here is just my guess. Try to change the last lines this way:
// ...
var firstrowcopy = 0;
for (var i = 0; i < data.length; i++){
if(data[i][1] == DetailD){ //[1] because column B
firstrowcopy = i+1;
break;
}
}
var source = DetailDEVIS.getRange(firstrowcopy,1,numrow-1);
var destination = DetailFactureDevis.getRange(lastrowpaste2,3);
source.copyTo(destination);
}

Reading values from input fields created in an array with document.createElement()

I'm trying to build a table that the user can hit "new line" to create a new row of the table. I do this by foo.push(document.createElement("INPUT"));
function newLine() {
sArr.push(document.createElement("INPUT"));
sArr[sArr.length-1].setAttribute("type", "text");
document.body.appendChild(sArr[sArr.length-1]);
gArr.push(document.createElement("INPUT"));
gArr[gArr.length-1].setAttribute("type", "text");
document.body.appendChild(gArr[gArr.length-1]);
tArr.push(document.createElement("INPUT"));
tArr[tArr.length-1].setAttribute("type", "text");
document.body.appendChild(tArr[tArr.length-1]);
//alert(sArr.length+", "+gArr.length+", "+tArr.length);
var x = document.createElement("br");
document.body.appendChild(x);
}
function calc(){
var temp = 0;
var total = 0;
for(i = 0; i<sArr.length; i++){
total = total + calc2(i);
}
var o = document.getElementById("output");
o.value = total;
}
function calc2(i){
alert(i);
var s = document.getElementById(sArr[i]);
var g = document.getElementById(gArr[i]);
var t = document.getElementById(tArr[i]);
var VO2walkmin = 3.28;
var VO2rest = 3.05;
var C1 = 0.32;
var C2 = 0.19;
var C3 = 2.66;
var Cdecline = 0.73;
var s2 = s.value;
var g2 = g.value;
var t2 = t.value;
var negGrade = g.value;
if(g2 < 0){g2 = 0};
VO2move = ((C1 * g2)+VO2walkmin)+((1+(C2*g2))*(C3*(s2^2)));
VO2inc = VO2rest+(t2*VO2move);
VO2dec = VO2rest+(Cdecline*(t2*VO2move))
//var o = document.getElementById("output");
return VO2inc;
}
When run, I get the error:
Uncaught TypeError: Cannot read property 'value' of null
from line 66. Specifically, this line:
var s2 = s.value;
I'm struggling to find my mistake here... and all help is appreciated.
You create a new element, but it has no ID. And so you can't fetch it by ID. The result of document.getElementById(sArr[i]) will be null.
Check this answer to see how ID can be assigned to a newly created element:
Create element with ID
There's no need to use document.getElementById. sArr[i] is the input element itself, not its ID, so you can just read its value directly.
var s = sArr[i];
var g = gArr[i];
var t = tArr[i];

Spreadsheet script doesn't run if the spreadsheet is shared

I'm working on a script that would copy a row from a big database and that way makes it easier to modify.
The main point would be to allow more editor to modify the database parallel. However, if I share the spreadsheet, other users get the following error: Script ... experienced an error. The user encounters this problem by scripts assigned to a button only. onEdit() runs just fine.
It's my first google script file, so I have really no idea that what's the problem and how should I solve it.
The whole code is here:
//copy the chosen row to the appropriate cells of the editor sheet
//if zero sets the cells to default
function copySelectedRow(){
var ss=SpreadsheetApp.getActiveSpreadsheet();
var shData=ss.getSheets()[0];
var shEdit=ss.getActiveSheet();
var idNumber = shEdit.getRange(1,2).getValue();
if(idNumber == 0) {
var arrayData = [["","","","","","","","","","","","","","","","","","","","","","","","",""]];
} else {
var rowNumber=findRow(idNumber);
if(rowNumber == -1) {
SpreadsheetApp.getUi().alert('Nincs ilyen betegszam!');
return;
}
var range1=shData.getRange(rowNumber,1,1,shData.getLastColumn());
var arrayData=range1.getValues();
}
var arrayDataT = new Array(new Array);
var arr = new Array(new Array);
var arrT = new Array(new Array);
arrayDataT = transpose(arrayData);
arrT = arrayDataT.slice(1,6);
arr = transpose(arrT);
shEdit.getRange(5,1,1,5).setValues(arr);
shEdit.getRange(2,4).setValue(arrayData[0][6]);
arrT = arrayDataT.slice(7,11);
shEdit.getRange(7,2,4).setValues(arrT);
arrT = arrayDataT.slice(7,11);
shEdit.getRange(7,2,4).setValues(arrT);
shEdit.getRange(7,3).setValue(arrayData[0][11]);
arrT = arrayDataT.slice(12,16);
shEdit.getRange(7,4,4).setValues(arrT);
arrT = arrayDataT.slice(16,20);
shEdit.getRange(12,2,4).setValues(arrT);
shEdit.getRange(12,3).setValue(arrayData[0][20]);
arrT = arrayDataT.slice(21,25);
shEdit.getRange(12,4,4).setValues(arrT);
}
//trasnspone a 2D array
function transpose(a)
{
return Object.keys(a[0]).map(function (c) { return a.map(function (r) { return r[c]; }); });
}
//save the cells to the database, checks and writes out if the editor is sure or unsure
function saveData() {
var app = SpreadsheetApp;
var shData = app.getActiveSpreadsheet().getSheets()[0];
var shEdit = app.getActiveSpreadsheet().getActiveSheet();
var idNumber = shEdit.getRange(1,2).getValue();
var row = findRow(idNumber);
if(row == -1) {
SpreadsheetApp.getUi().alert('Nincs ilyen betegszam!');
return;
}
var arr = new Array;
var arrT = new Array(new Array());
var arrayData = new Array(new Array());
var tempArray = new Array(new Array());
arrT = shEdit.getRange(7,2,4).getValues();
arr = transpose(arrT);
arrayData.push(arr);
arrT = shEdit.getRange(7,3).getValue();
tempArray[0][0] = arrT;
arrayData.push(tempArray);
arrT = shEdit.getRange(7,4,4).getValues();
arr = transpose(arrT);
arrayData.push(arr);
arrT = shEdit.getRange(12,2,4).getValues();
arr = transpose(arrT);
arrayData.push(arr);
arrT = shEdit.getRange(12,3).getValue();
tempArray[0][0] = arrT;
arrayData.push(tempArray);
arrT = shEdit.getRange(12,4,4).getValues();
arr = transpose(arrT);
arrayData.push(arr);
tempArray = new Array(new Array);
var count = 0;
for(var i=1; i<arrayData.length; i++){
for(var j=0; j<(arrayData[i][0].length); j++){
tempArray[0][count]=arrayData[i][0][j];
count++;
}
}
shData.getRange(row,8,1,18).setValues(tempArray);
var sure = shEdit.getRange(20,6).getValue();
if(sure) {
shData.getRange(row, 7).setValue("KÉSZ");
shEdit.getRange(2,4).setValue("KÉSZ");
} else {
shData.getRange(row, 7).setValue("BIZONYTALAN");
shEdit.getRange(2,4).setValue("BIZONYTALAN");
}
}
//returns the row number of the id value in the database
function findRow(idNumber) {
var app = SpreadsheetApp;
var shData = app.getActiveSpreadsheet().getSheets()[0];
var matchArray = shData.getRange("A:A").getValues();
for(var count=0; count<matchArray.length; count++){
if(matchArray[count][0]==idNumber) return count+1;
}
return -1;
}
//runs if the id cell is modified
function onEdit(e) {
var range = e.range;
var columnOfCellEdited = range.getColumn();
var rowOfCellEdited = range.getRow();
if (columnOfCellEdited === 2 && rowOfCellEdited === 1) {
copySelectedRow();
collision();
}
};
//increment the value of id by one
function incrementByOne() {
var app = SpreadsheetApp;
var targetSheet = app.getActiveSpreadsheet().getActiveSheet();
var tempNumber = targetSheet.getRange(1,2).getValue();
targetSheet.getRange(1, 2).setValue(tempNumber+1);
copySelectedRow();
collision();
}
//decrement the value of id by one
function decrementByOne() {
var app = SpreadsheetApp;
var targetSheet = app.getActiveSpreadsheet().getActiveSheet();
var tempNumber = targetSheet.getRange(1,2).getValue();
targetSheet.getRange(1, 2).setValue(tempNumber-1);
copySelectedRow();
collision();
}
//writes out if more editors are editing the same line
function collision(){
var ss=SpreadsheetApp.getActiveSpreadsheet();
var allSheets=ss.getSheets();
var idArray = new Array();
var temp;
for(var i=1; i<allSheets.length; i++){
temp = allSheets[i].getRange(1,2).getValue();
idArray.push(temp);
}
var collisionArray = new Array();
for(var i=0; i<idArray.length; i++){
for(var j=i+1; j<idArray.length; j++){
if(idArray[i] == idArray[j]){
collisionArray.push(i);
collisionArray.push(j);
}
}
}
for(var i=1; i<allSheets.length; i++){
allSheets[i].getRange(1,3).setValue("");
}
for(var i=0; i<collisionArray.length; i++){
allSheets[collisionArray[i]+1].getRange(1,3).setValue("SZERKESZTÉS ALATT");
}
}
So if I click the drawing that is associated with incrementByOne, it will give an error, but if I just change the cell, onEdit() can call the same functions easily.
(Sorry for the long code, I don't know which part could be important. If you tell me, I'll make it shorter.)
The solution:
If I share the code with a link, an anonymous editor can not use every script, because of authentication issues (don't ask why it isn't a problem by onEdit() ). Also, if the editor logs in into his/her gmail account and accepts everything, the script will become runable (but maybe a bit slower than on the owners account).

Save dynamically created table data to multidimensional array

I have a dynamically created table and I need to retrieve the values from that to be stored in a multidimensional array as shown below
But I am getting an exception/error saying "Cannot set property of 0 to undefined"
My JS Function:
var DefAttrArray = new Array(100);
function storeDefinedStreamInfo(newAgent,i,e,ui)
{
var StrName= document.getElementById("StreamNameInput").value;
var StreamElementID = i;
var table = document.getElementById('attrtable');
var tblerows = (table.rows.length)-1;
// DefAttrArray[i] = new Array(3);
// for (var w=3; w<3; w++)
// {
// DefAttrArray[q][w] = new Array(tblerows);
// }
for (r = 1; r < table.rows.length; r++) {
for(var c=0; c<1;c++) {
var attrNm = table.rows[r].cells[c].innerHTML;
var attrTp = table.rows[r].cells[1].innerHTML;
createdDefinedStreamArray[i-1][2][r-1]= new Array(2);
createdDefinedStreamArray[i-1][2][r-1][0]=attrNm;
createdDefinedStreamArray[i-1][2][r-1][1]=attrTp;
alert(createdDefinedStreamArray[i-1][2][r-1][0] + "\n" + createdDefinedStreamArray[i-1][2][r-1][1]);
}
}
createdDefinedStreamArray[i-1][0]=StreamElementID;
createdDefinedStreamArray[i-1][1]=StrName;
createdDefinedStreamArray[i-1][2]=new Array(tblerows);
createdDefinedStreamArray[i-1][3]="Defined Stream";
alert("createdDefinedStreamArray[i-1][2][w][0] : "+ createdDefinedStreamArray[i-1][2][w][0]);
var prop = $('<a class="streamproperty" onclick="doclickExp(this)"><b><img src="../Images/settings.png"></b></a> ').attr('id', (i));
var showIcon = $('<img src="../Images/Defined.png"></b></a> ').attr('id', (i));
newAgent.text(StrName).append('<a class="boxclose" id="boxclose"><b><img src="../Images/Cancel.png"></b></a> ').append(showIcon).append(prop);
dropCompleteElement(newAgent,e,ui);
}
Finally, got it to work.
var DefAttrArray = new Array(100);
function storeDefinedStreamInfo(newAgent,i,e,ui)
{
var StrName= document.getElementById("StreamNameInput").value;
var StreamElementID = i;
var table = document.getElementById('attrtable');
var tblerows = (table.rows.length)-1;
createdDefinedStreamArray[i][2]=new Array(tblerows);
for (r = 1; r < table.rows.length; r++) {
for(var c=0; c<1;c++) {
var attrNm = table.rows[r].cells[c].innerHTML;
var attrTp = table.rows[r].cells[1].innerHTML;
createdDefinedStreamArray[i][2][r-1]= new Array(2);
createdDefinedStreamArray[i][2][r-1][0]=attrNm;
createdDefinedStreamArray[i][2][r-1][1]=attrTp;
}
}
createdDefinedStreamArray[i][0]=StreamElementID;
createdDefinedStreamArray[i][1]=StrName;
createdDefinedStreamArray[i][3]="Defined Stream";
createdDefinedStreamArray[i][4]= tblerows;
var prop = $('<a class="streamproperty" onclick="doclickDefine(this)"><b><img src="../Images/settings.png"></b></a> ').attr('id', (i));
var showIcon = $('<img src="../Images/Defined.png"></b></a> ').attr('id', (i));
newAgent.text(StrName).append('<a class="boxclose" id="boxclose"><b><img src="../Images/Cancel.png"></b></a> ').append(showIcon).append(prop);
dropCompleteElement(newAgent,e,ui);
}

JS: Create Objects in loop with iterator

I want to create some objects like object_point1, object_point2, ...
with a for loop that split a string with x and y coords.
How can i use iterates to create the name of objects?
Thanks
var vMsg = req.body.myMessage;
var fields = vMsg.split(/\n/);
var myobjct = new Object();
myobject.PointCount=parseFloat(paramsCoords);
for (var ii=0; ii<fields.length; ii++)
{
var coord=fields[ii].split(/\t/);
//console.info ("X" + coord[0]);
//console.info ("Y" + coord[1]);
var object_Point[ii] = new Object();
object_Point[ii].x_m=parseFloat(coord[0]);
object_Point[ii].y_m=parseFloat(coord[1]);
myobject.Polygon_Point[ii]=object_Point[ii];
}
At the moment i use this construction:
for (var ii=0; ii
var coord=fields[ii].split(/\t/);
var objPolygon_Point = new Object()
objPolygon_Point["point" + ii] = new Object();
objPolygon_Point["point" + ii].x_m=parseFloat(coord[0]);
objPolygon_Point["point" + ii].y_m=parseFloat(coord[1]);
if (ii=='1')
{
myobject.Polygon_Point1=objPolygon_Point["point" + ii];
}
if (ii=='2')
{
myobject.Polygon_Point2=objPolygon_Point["point" + ii];
}
// ii==3, ii==4, .......
}
You can generate dynamic object names in the global scope like:
Browser:
var ii = 11
, x = 123
, y = 234;
window['Object_Point' + ii] = {
x : parseFloat(x),
y : parseFloat(y)
}
console.log(Object_Point11);
console.log(window.Object_Point11);
// Object {x: 123, y: 234}
node.js
> var i = 12;
> global['MyObj'+i] = { hello : 'world' };
> console.log(MyObj12);
> console.log(global.MyObj12);
// { hello: 'world' }
see node.js global variables?
But rather than using window or global, you might want to use your own object
> var i = 12, myObj = {};
> myObj['MyObj'+i] = { hello : 'world' };
> console.log(myObj.MyObj12);
// { hello: 'world' }
I directly used your example. I'll suggest to create middle-map object. I.e. something like holder of all the points. Using the global namespace is not a good practice.
var vMsg = req.body.myMessage;
var fields = vMsg.split(/\n/);
var myobjct = new Object();
myobject.PointCount=parseFloat(paramsCoords);
var points = {};
for (var ii=0; ii<fields.length; ii++)
{
var coord=fields[ii].split(/\t/);
//console.info ("X" + coord[0]);
//console.info ("Y" + coord[1]);
var point = points["point" + ii] = new Object();
point.x_m = parseFloat(coord[0]);
point.y_m = parseFloat(coord[1]);
myobject.Polygon_Point[ii] = point;
}

Categories

Resources