This is my first stab at trying to create a JavaScript object. I am attempting to extract properties from a very complex JSON response from a USGS REST service and save them as an object for later use.
What I am attempting to do is create an empty array as the first property of the object to later populate with instances of a custom object later, the last line of actual code. After digging around both the W3C, MDN and this site, I have yet to really come up with a solution.
Please feel free to not only offer solutions to the array issue, but also offer constructive criticism on the rest of the code. After all, I am trying to learn with this project.
// create site object
function Site(siteCode) {
this.timeSeriesList = [];
this.siteCode = siteCode
this.downloadData = downloadData;
// create timeSeries object
function TimeSeries(siteCode, variableCode) {
this.siteCode = siteCode;
this.variableCode = variableCode;
this.observations = [];
}
// create observation object
function TimeSeriesObservation(stage, timeDate) {
this.stage = stage;
this.timeDate = timeDate;
}
// include the capability to download data automatically
function downloadData() {
// construct the url to get data
// TODO: include the capability to change the date range, currently one week (P1W)
var url = "http://waterservices.usgs.gov/nwis/iv/?format=json&sites=" + this.siteCode + "&period=P1W¶meterCd=00060,00065"
// use jquery getJSON to download the data
$.getJSON(url, function (data) {
// timeSeries is a two item list, one for cfs and the other for feet
// iterate these and create an object for each
$(data.value.timeSeries).each(function () {
// create a timeSeries object
var thisTimeSeries = new TimeSeries(
this.siteCode,
// get the variable code, 65 for ft and 60 for cfs
this.variable.variableCode[0].value
);
// for every observation of the type at this site
$(this.values[0].value).each(function () {
// add the observation to the list
thisTimeSeries.observations.push(new TimeSeriesObservation(
// observation stage or level
this.value,
// observation time
this.dateTime
));
});
// add the timeSeries instance to the object list
this.timeSeriesList.push(thisTimeSeries);
});
});
}
}
If you would like to view the JSON I am using for testing, you can find it here: http://waterservices.usgs.gov/nwis/iv/?format=json&sites=03479000&period=P1W¶meterCd=00060,00065
Thank you in advance for your time and mentoring!