javascript - unable to populate 2D array - javascript

My instructor tasked us to build a 2D array and populate it with values from our HTML form. He gave us this example to create the array.
var tasks = new Array();
var index = 0;
He then said to insert the values into the two columns using this code.
tasks[index]["Date"] = tempdate;
tasks[index]["Task"] = temptask;
However, something about these two lines is causing the script to break, because when I comment them out the final line of my script returns a value to the correct div. When I uncomment these lines no value is returned. Is there something wrong in my syntax?
This is my complete js file:
var tasks = new Array();
var index = 0;
function addTask() {
var tempdate = new Date();
var temptask = document.getElementById("taskinfo").value;
var td = document.getElementById("taskdate").value;
tempdate = td + " 00:00";
tasks[index]["Date"] = tempdate;
tasks[index]["Task"] = temptask;
index++
tasks.sort(function (a, b) { return b.date - a.date });
var tablecode = "<table class = 'tasktable'>" +
"<tr>"+
"<th>Date</th>"+
"<th>Task</th>"+
"</tr>";
for (var i = 0; i < tasks.length; i++) {
tablecode = tablecode + "<tr>" +
"<td>" + tasks[i]["Date"].toDateString() + " </td>" +
"<td>" + tasks[i]["Task"] + " </td>" +
"</tr>";
}
tablecode = tablecode + "</table>";
//I am only returning "temptask" to test with, I will be returning "tablecode".
document.getElementById("bottomright").innerHTML = temptask;
return false;
}

tasks[index] (in the first case, tasks[0]) doesn't yet exist, so you can't give it properties. Try this to create an object and assign it to tasks[index]:
tasks[index] = {
Date: tempdate,
Task: temptask
};
in place of
tasks[index]["Date"] = tempdate;
tasks[index]["Task"] = temptask;
Alternatively, you can use
tasks[index] = {};
tasks[index]["Date"] = tempdate;
tasks[index]["Task"] = temptask;

Related

Issues attempting to display data from JSON file

Premise:
I'm playing around with javascript and have been trying to display a populated JSON file with an array of people on the browser. I've managed to display it through ajax, but now I'm trying to perform the same task with jQuery.
Problem:
The problem is that it keeps saying customerdata[i] is undefined and can't seem to figure out why.
$(function() {
console.log('Ready');
let tbody = $("#customertable tbody");
var customerdata = [];
$.getJSON("MOCK_DATA.json", function(data) {
customerdata.push(data);
});
for (var i = 0; i < 200; i++) {
//Cell for name
let nameTD = $('<td>').text(customerdata[i].first_name + ", " + customerdata[i].last_name);
//Cell for birthdate
let mDate = moment(customerdata[i].birthdate);
let formattedmDate = mDate.format('YYYY-MM-DD');
let birthdateTD = $('<td>').text(formattedmDate);
//Cell for Address
let addressTD = $('<td>').html("City: " + customerdata[i].city + '<br>' + "Email: " + customerdata[i].email + '<br>' + '<a href=' + customerdata[i].website + '>Website</a>');
//Cell for Credits
let creditTD = $('<td>').text(customerdata[i].credits);
let row = $('<tr>').append(nameTD).append(birthdateTD).append(addressTD).append(creditTD);
tbody.append(row);
}
})
SAMPLE CONTENT OF MOCK_DATA.json
[
{"id":1,"first_name":"Tracey","last_name":"Jansson","email":"tjansson0#discuz.net","gender":"Female","ip_address":"167.88.183.95","birthdate":"1999-08-25T17:24:23Z","website":"http://hello.com","city":"Medellín","credits":7471},
{"id":2,"first_name":"Elsa","last_name":"Tubbs","email":"etubbs1#uol.com.br","gender":"Female","ip_address":"61.26.221.132","birthdate":"1999-06-28T17:22:47Z","website":"http://hi.com","city":"At Taḩālif","credits":6514}
]
Firstly, you're pushing an array into an array, meaning you're a level deeper than you want to be when iterating over the data.
Secondly, $.getJSON is an asynchronous task. It's not complete, meaning customerdata isn't populated by the time your jQuery is trying to append the data.
You should wait for getJSON to resolve before you append, by chaining a then to your AJAX call.
$.getJSON("MOCK_DATA.json")
.then(function(customerdata){
for(var i = 0; i < 200; i++){
//Cell for name
let nameTD = $('<td>').text(customerdata[i].first_name + ", " + customerdata[i].last_name);
//Cell for birthdate
let mDate = moment(customerdata[i].birthdate);
let formattedmDate = mDate.format('YYYY-MM-DD');
let birthdateTD = $('<td>').text(formattedmDate);
//Cell for Address
let addressTD = $('<td>').html("City: " +
customerdata[i].city + '<br>' + "Email: " +
customerdata[i].email + '<br>' + '<a
href='+customerdata[i].website+'>Website</a>');
//Cell for Credits
let creditTD = $('<td>').text(customerdata[i].credits);
let row = $('<tr>').append(nameTD).append(birthdateTD).append(addressTD).append(creditTD);
tbody.append(row);
}
})
You also won't need to define customerdata as an empty array at all with this approach.
The problem is that data is already an array.
so you should use:
customerdata = data;
otherwhise you are creating an array in the pos 0 with all the data

How to remove empty values from array in google docs script

I am trying to print out the values of the array in a google doc. I do get the correct values but it goes on printing out a number of "undefined" values. The simplest way is probably to filter out the undefined values before I print out the array.
Here is the array declaration:
var paramArr = Object.keys(e.parameter).reverse();
var tableArr = [];
for(var i = 0; i < paramArr.length - 1; i++) {
var tempArr;
var nameSelector = "Company:" + i;
var startDateSelector = "Started:" + i;
var endDateSelector = "Ended:" + i;
var referenceSelector = "Reference:" + i;
var descriptionSelector = "Description:" + i;
tempArr = [e.parameter[nameSelector] + " ",
e.parameter[startDateSelector] + " - " +
e.parameter[endDateSelector]+ "\n\n" +
e.parameter[descriptionSelector]
];
I have tried this, but it doesn't work:
tempArr = tempArr.filter(function(element){
return element !== undefined;
});

Export array of objects into Excel using Javascript

I'm writing a client side method, that creates an array of objects.I open an existing excel to write the values from the array. I get the values using getProperty and store in a variable.
When I try to write those in the excel, I get "event handler failed with message";" ".
Code:
var getItemtoExcel = document.thisItem.newItem("ToExcel", "get");
getItemtoExcel = getItemtoExcel.apply();
var arrToExcel = Array();
for (var j = 0; j < getItemtoExcel.getItemCount(); j++) {
var gotItemForExcel = getItemtoExcel.getItemByIndex(j);
arrToExcel.push(gotItemForExcel);
}
var Excel = new ActiveXObject("Excel.Application");
Excel.Visible = true;
Excel.Workbooks.Open("C:\\test.xls");
var offset = 0;
var row = 2;
for (var c = 0; c < arrToExcel.length; c++) {
var createExcel = arrToExcel[c];
var Number = createExcel.getProperty("nb");
var Type = createExcel.getProperty("type");
var Code = createExcel.getProperty("code");
var State = createExcel.getProperty("state");
Excel.Worksheets("sheet11").Range("A" & row + 1 + offset).Value = Number;
Excel.Worksheets("sheet11").Range("B" & row + 1 + offset).Value = Type;
Excel.Worksheets("sheet11").Range("C" & row + 1 + offset).Value = Code;
Excel.Worksheets("sheet11").Range("D" & row + 1 + offset).Value = State;
row = row + 1;
}
offset = offset + 1;
return this;
document.thisItem.newItem() is from ARASPLM. Its the standard used to call an ItemType(Item) in ARAS
If you have an opportunity to use SheetJS, it's pretty straightforward
Firstly, Install xlsx package npm install --save xlsx
const XLSX = require('xlsx')
// array of objects to save in Excel
let binary_univers = [{'name': 'Hi','value':1},{'name':'Bye','value':0}]
let binaryWS = XLSX.utils.json_to_sheet(binary_univers);
// Create a new Workbook
var wb = XLSX.utils.book_new()
// Name your sheet
XLSX.utils.book_append_sheet(wb, binaryWS, 'Binary values')
// export your excel
XLSX.writeFile(wb, 'Binaire.xlsx');
i think using this you can get what you want but you need to pass the your Object's value with this that i have mentioned here as (Your Data(Object))
window.open('data:application/vnd.ms-excel,' + **(Your Data(Object))**);
here i'm providing simple code for get data into excel format with jquery
SAMPLE DEMO
Thanks for all your suggestions on this question.
I have done with exporting the array into a .csv file successfully.
Here's the code, for others who will need.
var getItemtoExcel=this.newItem("MyForm", "get");
getItemtoExcel=getItemtoExcel.apply();
var arrToExcel = Array();
for (var j=0; j<getItemtoExcel.getItemCount(); j++)
{
var gotItemForExcel=getItemtoExcel.getItemByIndex(j);
arrToExcel.push(gotItemForExcel);
}
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("C:\\REPORT.csv", true);
var title="Report";
s.WriteLine(title);
var header="Number" + ";" + "Type" + ";" + "Code" + ";" + "Created On" + ";" + "State" + '\n' ;
s.WriteLine(header);
for (var c=0; c<arrToExcel.length; c++){
var createExcel = arrToExcel[c];
var Number =createExcel.getProperty("nb");
var Type=createExcel.getProperty("type");
if(Type===undefined){Type="";}
var Code=createExcel.getProperty("code");
if(Code===undefined){Code="";}
var Date=createExcel.getProperty("created_on");
var State=createExcel.getProperty("created_by_id/#keyed_name");
var value=Number + ";" + Type + ";" + Code + ";" + Date + ";" + State;
s.WriteLine(value);
}
s.Close();
alert("Report Saved as C:\\REPORT.csv");
return this;

Nested for loop for printing a 2d array. Ist iteration undefined?

I have tried many variations of the code below i.e swapping in while. I have an array that is created and added to dynamically. It creates an empty league table. When I iterate through the array and print out the table the first loop always comes back undefined? I have console logged everything but cannot work out why. I think it is to do with the inner loop variable but am running out of ideas. Can someone explain why this happens on all the loops? I have read questions on here and some talk about the variable being treated as string on the first loop but did not understand.
league = [];
$('#butt').on('click',function(){
var name = $('.input1').val();
x = $('#demo');
x.html(name);
person(name,0,0,0,0,0);
});
function person(first,w,d,l,gf,ag) {
this.Name = first;
this.wins = w;
this.draws = d;
this.lose = l;
this.goalsfor = gf;
this.goalsag =ag;
newTeam = new Array
(this.Name,this.wins,this.draws,this.lose,this.goalsfor,this.goalsag);
league.push(newTeam);
teamRow = league[0][0];
makeLeague();
}
function makeLeague(){
var tableStart = "<table>"
var tableEnd = "</table>"
var tableMid ;
var secondtab = $('#demo1');
leagueSize = league.length;
console.log("league length is " + league.length);
for(k=0; k<league.length; k++){
tableMid += "<tr>";
for(i=0; i< 6; i++){
tableMid += "<td> " + league[k][i] + "</td>";
}
tableMid += "</tr>";
}
secondtab.html(tableStart + tableMid + tableEnd);
}
You're using person as a normal function when it should be used as a constructor. Try using new person(name, 0, 0, 0, 0, 0); instead (and perhaps storing it to a variable).
In addition, as John Sheridan mentions, you need to also initialize your tableMid variable before you can append to it, as follows: var tableMid = "";.
Here's a cleaned-up version of the code. Note the var declarations that you should include to avoid scoping issues.
var league = [];
$('#butt').on('click', function() {
var name = $('.input1').val();
var x = $('#demo');
x.html(name);
var person = new Person(name, 0, 0, 0, 0, 0);
});
function Person(first, w, d, l, gf, ag) {
this.Name = first;
this.wins = w;
this.draws = d;
this.lose = l;
this.goalsfor = gf;
this.goalsag = ag;
var newTeam = [this.Name, this.wins, this.draws, this.lose, this.goalsfor, this.goalsag];
league.push(newTeam);
var teamRow = league[0][0];
makeLeague();
}
function makeLeague() {
var tableStart = "<table>";
var tableEnd = "</table>";
var tableMid = "";
var secondtab = $('#demo1');
for (var k = 0; k < league.length; k++) {
var team = league[k];
tableMid += "<tr>";
for (var i = 0; i < team.length; i++) {
tableMid += "<td> " + team[i] + "</td>";
}
tableMid += "</tr>";
}
secondtab.html(tableStart + tableMid + tableEnd);
}
In your makeLeague() function you should initialize tableMid before using it in the += operations.
var tableMid = '';
Without this tableMid is undefined.
your error comes from league.length being 0 at the for-loop.
thats why the loop never gets executed, so tableMid is undefined.
you initialize league at start with
league = [];
that makes it a non-global variable.
initialize it with
var league[];
at start, that should work.
Additionally you need to initialize tableMid with a empty string, like John Sheridan mentioned, or the addition will fail as undefined.
var tableMid = "";
DEMO
[edit] sry wrong link

Javascript - passing returned variable to another function

I am trying to pass my results value from to projectYears() function to projectInvestment() function that will then write to the div tag. I am getting the error "result is not defined error". To me this makes sense. All the code is working as intended. Can someone please let me know how to achieve this.
function projectInvestment(nameId, investmentId, interestId, yearsId, amountId) {
var inputName = document.getElementById(nameId).value;
var inputInvestment = parseFloat(document.getElementById(investmentId).value);
var inputInterest = parseFloat(document.getElementById(interestId).value);
var inputYears = parseInt(document.getElementById(yearsId).value);
var inputAmount = parseFloat(document.getElementById(amountId).value);
projectYears(inputInvestment, inputInterest, inputYears);
var outputString = projectYears(result);
document.getElementById("outputDiv").innerHTML = outputString;
}
function projectYears(inInvest, inInterest, inYears) {
var interest = parseFloat(inInterest / 100);
var interestAmt = parseFloat(inInvest * interest);
var predictedInvest = parseFloat(inInvest + interestAmt);
var result = "<br /> Investment Schedule for <b>$" + inInvest.toFixed(2) +
" </b>at <b>" + inInterest + "% </b>annual interest for <b>" + inYears + "</b> years <br /><br />";
result += "<table border='1' align='center'><tr><th>Year</th><th>Amount</th>";
//for loop to loop through the years
for (var x = 1; x <= inYears; x++) {
result += "<tr><td>" + x + "</td><td>" + predictedInvest.toFixed(2) + "</td></tr>";
interestAmt = predictedInvest * interest;
predictedInvest = (predictedInvest + interestAmt);
}
result += "</table>";
return result;
//document.getElementById("outputDiv").innerHTML = result;
}
You are passing in a variable called result that isn't defined.
See this line in the projectInvestment function:
var outputString = projectYears(result);
It looks like, based on the function definition for projectYears, you should be passing in some of the variables you create above this line instead.
i.e.
var outputString = projectYears(inputInvestment, inputInterest, inputYears);
var inputAmount = parseFloat(document.getElementById(amountId).value);
var outputString = projectYears(inputInvestment, inputInterest, inputYears);
document.getElementById("outputDiv").innerHTML = outputString;

Categories

Resources