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;
}
}
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.
var myjsonObj = '[{"location":"Helsinki", "temperature":4},
{"location":"Tokyo", "temperature":26}]';
var jsObj = JSON.parse(myjsonObj);
console.log(jsObj[0].location);
console.log(jsObj[0].temperature);
var observationsArray = [];
function init() {
if (localStorage.observationsRecord) {
observationsArray = JSON.parse(localStorage.observationsRecord);
for (var i = 0; i < observationsArray.length; i++) {
prepareTableCell(observationsArray[i].location, observationsArray[i].temperature);
}
}
}
function onRegisterPressed() {
var locationName = document.getElementById("location").value;
var temperatureValue = document.getElementById("temperature").value;
var stuObj = {
location: locationName,
temperature: temperatureValue
};
observationsArray.push(stuObj);
localStorage.observationsRecord = JSON.stringify(observationsArray);
prepareTableCell(locationName, temperatureValue);
document.getElementById("location").value = "";
document.getElementById("temperature").value = "";
}
function prepareTableCell(locationName, temperatureValue) {
var table = document.getElementById("regtable");
var row = table.insertRow();
var locationNameCell = row.insertCell(0);
var temperatureValueCell = row.insertCell(1);
locationNameCell.innerHTML = locationName;
temperatureValueCell.innerHTML = temperatureValue;
//firstNameCell.colSpan = 2;
}
Hello! I'm fairly new to web development and I've been following a guide on TechThree INFO's youtube channel. I have created an html form that submits the data to local storage. My next step is to display the lowest and highest temperatures from specified locations (in the past 24hrs) and also the current temperature from each location. I am currently clueless on how to display the data from local storage.
To get data from your localStorage, you can use localStorage.getItem(key)
This will return your stringified JSON, so you'll need to parse that back to a JS Object.
var observations = JSON.parse(localStorage.getItem('observationsRecord'))
Finally, you want to find highest and lowest temperatures.
var max = {
location: '',
temperature: 0
};
var min = {
location: '',
temperature: 0
};
for(var i = 0; i < observations.length; i++) {
if(observations[i].temperature > max) {
max.location = observations[i].location;
max.temperature = observations[i].temperature;
}
if(observations[i].temperature < min) {
max.location = observations[i].location;
min.temperature = observations[i].temperature;
}
}
Your highest temperature will be stored in max, and your lowest in min.
Hope this helps :)
Am trying to print the dynamic data into the PDF using jsPdf AutoTable .But am failed to do that. I searched in many site's but no one didn't said about dynamic data into the Row's. So here my question is , Is there any way to get the Dynamic data into the table row's if it so can some one clarify me pls . Note : [ Here am not using HTML to store the Data into the Pdf, i got the data from the js directly ] .
this.print=function(){
{
var mainData =this.printData(); // Here am getting Full Json data Here
var steps = mainData.steps; // From that data am Separating what i need
var criticality = mainData.criticality;
var categories = mainData.categories;
var checkup = mainData.checkup;
// This is For to Take the Steps Data alone
$scope.getSteps = function(steps) {
var data = [];
for (var i = steps.length; i-- > 0;) {
data.push(steps[i].name+"\n"+"\n");
}
return data;
}
// Like wise am getting every single object data's
$scope.getNumbersOfSubSteps = function(steps) {
var data = 0;
for (var i = 0 ; i < steps.length; i++) {
for (var j = 0; j<steps[i].steps.length; j++) {
}
data = j ;
}
return data;
}
// this is for Sub Proceeses
$scope.getSubProcesses = function(steps) {
var data = [];
for (var i = 0 ; i < steps.length; i++) {
for (var j = 0; j<steps[i].steps.length; j++) {
data.push(steps[i].steps[j].name+"\n");
}
}
return data;
}
$scope.getCategories = function(categories) {
var data = [];
for (var i = categories.length; i-- > 0;) {
data.push(categories[i].name+"\n");
}
return data;
}
$scope.getCriticality = function(criticality) {
var data = [];
for (var i = criticality.length; i-- > 0;) {
data.push(criticality[i].name+"\n");
}
return data;
}
// Pdf Print Function Begins
var columns = ["ProcessDescription", "Steps", "#ofSubProcesses", "SubSteps","Category","Criticality","CheckUp"];
var processDescription =mainData.description;
var processes= $scope.getSteps(steps);
var NoOfSubProcess = $scope.getNumbersOfSubSteps(steps);
var subProcesses = $scope.getSubProcesses(steps);
console.log('Subprocsses length',subProcesses);
var categories = $scope.getCategories(categories);
var criticality = $scope.getCriticality(criticality);
// The Problem Begins here , Am struggling to Get the Separate data's here !
var rows = [
[processDescription,processes,NoOfSubProcess,subProcesses,categories,criticality]
];
var pdfsize='a1';
var doc = new jsPDF('p', 'pt',pdfsize);
doc.autoTable(columns, rows, {
theme: 'striped', // 'striped', 'grid' or 'plain'
styles: {
overflow: 'linebreak',
columnWidth: 'wrap'
},
beforePageContent: function(data) {
doc.text("Process Name :"+mainData.name, 40, 30);
},
columnStyles: {
1: {columnWidth: 'auto'}
}
});
doc.save(mainData.name+ pdfsize +".pdf");
}
};
You will need to replace this:
var rows = [
[processDescription,processes,NoOfSubProcess,subProcesses,categories,criticality]
];
with something like this:
var rows = [];
for (var k = 0 ; k < processes.length; k++) {
rows.push([
processDescription,
processes[k],
NoOfSubProcess,
subProcesses[k],
categories[k],
criticality[k]
]);
};
The rows parameter should be an array of arrays. What you are putting in there is basically an array of an array of arrays if I understood correctly.
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.
Can anyone tell me why I'm getting this error for the code below:
Uncaught TypeError: Cannot set property '0' of undefined
var vehicles = [];
$.get('../poll/index.php?data=vehicles', function(data) {
var rows = $(data).find('row').length;
for (var i = 0; i < rows; i++) {
vehicles[i][0] = $(data).find('row').eq(i).find('stage').text();
vehicles[i][1] = $(data).find('row').eq(i).find('direction').text();
vehicles[i][2] = $(data).find('row').eq(i).find('stageName').text();
vehicles[i][3] = $(data).find('row').eq(i).find('atco').text();
vehicles[i][4] = $(data).find('row').eq(i).find('service').text();
vehicles[i][5] = $(data).find('row').eq(i).find('journey').text();
vehicles[i][6] = $(data).find('row').eq(i).find('fleet').text();
vehicles[i][7] = $(data).find('row').eq(i).find('longitude').text();
vehicles[i][8] = $(data).find('row').eq(i).find('latitude').text();
vehicles[i][9] = $(data).find('row').eq(i).find('operator').text();
vehicles[i][10] = $(data).find('row').eq(i).find('position').text();
}
}, 'xml');
You need to define each child array, e.g.
var vehicles = []; // parent array;
vehicles[0] = []; // first child array;
so you would need:
for (var i = 0; i < rows; i++) {
var vehicles[i] = [];
... rest of code here ...
}
vehicles[i] has no value assigned to it.
Add a line:
vehicles[i] = [];
at the top of the loop.