Let us say I have an object Airport with members airportCode and airportCity like this:
function Airport(airportCode, airportCity) {
this.airportCode = airportCode;
this.airportCity = airportCity;
};
How can I create an array of objects Airport to which I can add. In Java, this would work like this:
while(st.hasMoreTokens()) {
Airport a = new Airport();
a.airportCode = st.nextToken();
a.airportCity = st.nextToken();
airports.add(a);
}
A very short answer:
airports.push(new Airport("code","city"));
Try this:
function Airport(airportCode, airportCity) {
this.airportCode = airportCode;
this.airportCity = airportCity;
};
var dataArray = [];
for(var i=0; i< 10; i++){
dataArray[i] = new Airport("Code-" + i, "City" + i);
}
It's not really that different
var airports = [];
while (st.hasMoreTokens()) {
var a = new Airport();
a.airportCode = st.nextToken();
a.airportCity = st.nextToken();
airports.push(a);
}
Related
So... The problem I have according to the console is:
"Uncaught TypeError: Cannot read property 'title' of undefined
at custom.js:42, at Array.forEach (), at custom.js:39"
How is "title" undefined? What's wrong with my .forEach? (sad noises)
Example of first of six objects in the JSON-array I've built:
var newReleases = [
{
"title":"Honor - Defending the motherland",
"author":"Mark Thomas",
"genre":"Fiction",
"description":"In legislation and formal documents the suffix shire was generally not used: for example, Bedfordshire was referred to as the administrative county of Bedford and the Northamptonshire council as the county council of Northampton.The 1888 Act did not contain a list of administrative counties: it was not until 1933 and the passing of a new Local Government Act."},
For loop with forEach function:
for (var i = 0; i < 6; i++){
newReleases.forEach (function (newReleases) {
var bookTitle = document.getElementsByClassName('card-header')
var t = document.createTextNode(newReleases[i].title);
bookTitle.appendChild(t);
var bookAuthor = document.getElementsByClassName('card-title')
var a = document.createTextNode(newReleases[i].authors);
bookAuthor.appendChild(a);
var cardGenre = document.getElementsByClassName("card-subtitle");
var genre = document.createTextNode(newReleases[i].genre);
cardGenre.appendChild(genre);
var cardDescr = document.getElementsByClassName('card-text');
var p = document.createTextNode(newReleases[i].description);
cardDescr.appendChild(p);
}) //end of forEach
} // end of for-loop
Use either for or forEach(), not both.
for (var i = 0; i < newReleases.length; i++) {
var bookTitle = document.getElementsByClassName('card-header')[0]
var t = document.createTextNode(newReleases[i].title);
bookTitle.appendChild(t);
var bookAuthor = document.getElementsByClassName('card-title')[0]
var a = document.createTextNode(newReleases[i].authors);
bookAuthor.appendChild(a);
var cardGenre = document.getElementsByClassName("card-subtitle")[0];
var genre = document.createTextNode(newReleases[i].genre);
cardGenre.appendChild(genre);
var cardDescr = document.getElementsByClassName('card-text')[0];
var p = document.createTextNode(newReleases[i].description);
cardDescr.appendChild(p);
}
or
newReleases.forEach(function(release) {
var bookTitle = document.getElementsByClassName('card-header')[0]
var t = document.createTextNode(release.title);
bookTitle.appendChild(t);
var bookAuthor = document.getElementsByClassName('card-title')[0]
var a = document.createTextNode(release.authors);
bookAuthor.appendChild(a);
var cardGenre = document.getElementsByClassName("card-subtitle")[0];
var genre = document.createTextNode(release.genre);
cardGenre.appendChild(genre);
var cardDescr = document.getElementsByClassName('card-text')[0];
var p = document.createTextNode(release.description);
cardDescr.appendChild(p);
});
When you use forEach() you don't need to subscript the array variable, you just use the parameter to the callback function.
I have a question. How can I initialize my var ingredientes = []; inside of the object "receita"? Is it done like I did? Or do I have to initialize it inside instead of outside?
var receitas = [];
var ingredientes = [];
var ingrediente = {
constructor: function(aNome, aQuantidade){
this.nome=aNome;
this.quantidade=aQuantidade;
}
};
var receita = {
constructor: function(aTipo, aNome, aTempo, aCusto, aDificuldade,
aDescricao, aIngredientes){
this.nome=aNome;
this.tipo=aTipo;
this.tempo=aTempo;
this.custo=aCusto;
this.dificuldade=aDificuldade;
this.descricao=aDescricao;
this.ingredientes=aIngredientes;
}
}
Thanks for any response!
I guess what you're actually looking for are classes, try doing this;
var receitas = [];
var ingredientes = [];
class Receita {
constructor(aTipo, aNome, aTempo, aCusto, aDificuldade, aDescricao, aIngredientes) {
this.nome = aNome;
this.tipo = aTipo;
this.tempo = aTempo;
this.custo = aCusto;
this.dificuldade = aDificuldade;
this.descricao = aDescricao;
this.ingredientes = aIngredientes;
}
}
class Ingrediente {
constructor(aNome, aQuantidade) {
this.nome = aNome;
this.quantidade = aQuantidade;
}
}
So to add an ingrediente to the ingredientes array you should do something like this:
var newReceita = new receita('Bolo', 'Bolo de fubá');
ingredientes = [
new ingrediente('Farinha', 300),
new ingrediente('Ovos', 2)
]
receita.ingredientes = ingredientes;
receita.constructor(...) will create all the properties within receita.
I am looping through an array and getting the data that I need.
for (var i = 0; i < finalArray.length; i++) {
var merchName = finalArray[i].merchName;
var amName = finalArray[i].amName;
var amEmail = finalArray[i].amEmail;
var txnID = finalArray[i].transID;
var transAccount = finalArray[i].transAccount;
}
What I am trying to do at this point is only show unique data in the loop.
For example var transAccount could be in the array 5 times. I only one to display that in my table once. How can I go about accomplishing this ?
Final Array is constructed like so; just as an object:
finalArray.push({
transID: tmpTrans,
transAccount: tmpAccount,
amEmail: amEmail,
merchName: merchName,
amPhone: amPhone,
amName: amName
});
var allTransAccount = {};
for (var i = 0; i < finalArray.length; i++) {
var merchName = finalArray[i].merchName;
var amName = finalArray[i].amName;
var amEmail = finalArray[i].amEmail;
var txnID = finalArray[i].transID;
var transAccount = finalArray[i].transAccount;
if(allTransAccount[finalArray[i].transAccount]) {
var transAccount = '';
}
else {
allTransAccount[transAccount] = true;
}
}
var merhcData = {};
var amName = {};
// and so on
for (var i = 0; i < finalArray.length; i++) {
merchData[finalArray[i].merchName] = finalArray[i].merchName;
amName[finalArray[i].amName] = finalArray[i].amName;
// and so on
}
If you are sure, that data in merchName will never be equal amName or other field - you can use one data object instead of several (merchData, amName...)
What you want is likely a Set. (see zakas for ES6 implementation. To emulate this using javascript, you could use an object with the key as one of your properties (account would be a good bet, as aperl said) which you test before using your raw array.
var theSet={};
for (var i = 0; i < finalArray.length; i++) {
var transAccount = finalArray[i].transAccount;
var merchName = finalArray[i].merchName;
var amName = finalArray[i].amName;
var amEmail = finalArray[i].amEmail;
var txnID = finalArray[i].transID;
if(!theSet[transAccount]){
//add to your table
theSet[transAccount]===true;
}
This will prevent entries of duplicate data.
I start with a short array of some schools and then I want to test if the value of an input matches one of these schools.
Here is my code thus far:
var $schools = [
'University of Tennessee-Knoxville',
'Maryville College',
'Cleveland State Community College',
'East Tennessee State University'
];
var $searchBar = $('input.searchBar');
$searchBar.keyup(function(){
var $searchValue = $searchBar.val();
for (var x = 0; x < $schools.length; x++) {
var $schoolLC = $schools[x].toLowerCase();
var $searchLC = $searchValue.toLowerCase();
var $searchingValue = new RegExp('.*' + $searchLC + '.*');
if ($schoolLC.match($searchingValue)) {
console.log($searchLC);
}
}
});
But something is obviously wrong (I believe with my RegExp), because it never console.logs the $searchLC.
Thanks so much!!
Isn't this
if ($searchLC.match($searchingValue)) {
supposed to be
if ($schoolLC.match($searchingValue)) {
I think you need to escape all RegEx special characters:
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
...
var $searchingValue = new RegExp('.*' + escapeRegExp($searchLC) + '.*');
...
Try this out: Live Demo
for (var x = 0; x < $schools.length; x++) {
var $schoolLC = $schools[x].toLowerCase();
var $searchLC = $searchValue.toLowerCase();
var $searchingValue = new RegExp('.*' + $searchLC + '.*');
if ($schoolLC.match($searchingValue)) {
alert($schoolLC);
}
}
Well, for this particular example, instead of using match you can use indexOf so that your code becomes
var $schools = [
'University of Tennessee-Knoxville',
'Maryville College',
'Cleveland State Community College',
'East Tennessee State University'
];
var $searchBar = $('input.searchBar');
$searchBar.keyup(function(){
var $searchValue = $searchBar.val();
for (var x = 0; x < $schools.length; x++) {
var $schoolLC = $schools[x].toLowerCase();
var $searchLC = $searchValue.toLowerCase();
if ($schoolLC.indexOf($searchLC) >= 0) {
console.log($searchLC);
}
}
});
I have an XML file, which can be viewed here, of data concerning a series of music albums, which I would like to load into javascript into an array called "mymusic" in this form:
mymusic = [
{
title:,
artist:,
artwork:,
tracks: [
{
tracktitle:,
trackmp3:
},
{
tracktitle:,
trackmp3:
}
]
}
];
etc.; so basically an array of albums, where each album is represented by a record, the fields of which are the album title, album artist, album artwork, and an array of the album's tracks (where each track/index of the array is represented by a record with fields tracktitle and trackmp3.
In order to achieve this I have the following javascript:
function getxml(){
xmldoc = XML.load('music.xml');
var xmlalbums = xmldoc.getElementsByTagName('album');
mymusic = [];
for(i = 0; i < xmlalbums.length; i++){
xmlalbum = xmlalbums[i];
mymusic[i] = {};
mymusic[i].title = dataFromTag(xmlalbum,'title');
mymusic[i].artist = dataFromTag(xmlalbum,'artist');
mymusic[i].artwork = dataFromTag(xmlalbum, 'artwork');
tracks = [];
var xmltracks = xmlalbums[i].getElementsByTagName('track');
for(var a = 0; a < xmltracks.length; a++){
xmltrack = xmltracks[i];
tracks[i] = {};
tracks[i].tracktitle = dataFromTag(xmltrack, 'title');
tracks[i].trackmp3 = dataFromTag(xmltrack, 'mp3');
mymusic[i].tracks = tracks;
}
}
}
however, this doesn't load the contents of music.xml in the way I'd like, but I can't see why this is. Any suggestions or help would be appreciated.
Thanks
that's should work
function getxml(){
xmldoc = XML.load('music.xml');
var xmlalbums = xmldoc.getElementsByTagName('album');
mymusic = [];
for(i = 0; i < xmlalbums.length; i++){
xmlalbum = xmlalbums[i];
mymusic[i] = {};
mymusic[i].title = dataFromTag(xmlalbum,'title');
mymusic[i].artist = dataFromTag(xmlalbum,'artist');
mymusic[i].artwork = dataFromTag(xmlalbum, 'artwork');
tracks = [];
var xmltracks = xmlalbums[i].getElementsByTagName('track');
for(var a = 0; a < xmltracks.length; a++){
xmltrack = xmltracks[a];
tracks[a] = {};
tracks[a].tracktitle = dataFromTag(xmltrack, 'title');
tracks[a].trackmp3 = dataFromTag(xmltrack, 'mp3');
}
mymusic[i].tracks = tracks;
}
}