Using Nested forEach Loops, JSON.stringify() & the Date Object

Share on facebook
Share on google
Share on twitter
Share on linkedin
JavaScript Date Objects

Following on from my previous blog entry about JSON, Async/await and hiding an API Key, this blog contains notes about using:

  • the JavaScript Date Object
  • JSON.stringify()
  • Nested forEach loops

All of the below have been implemented when completing the second core feature of the JavaScript weather manager: show London’s 5 day forecast on the page.

The aim

The data for 5 days of London weather can be obtained in JSON format. Here’s a sample: https://samples.openweathermap.org/data/2.5/forecast?id=524901&appid=b6907d289e10d714a6e88b30761fae22

The listkey’s value is an array of 40 objects, containing information about the weather in 3 hour increments for the current day and next four days. In each object is a key called dt_txt, which contains a string with the date and time the forecast is for. Each value is unique throughout the 40 objects.

"dt_txt": "2019-01-08 21:00:00"

The overall aim was to abstract the data needed from the selected object to display on index.html, such as the temperature, description of the temperature, and the icon).

In order to do this, the first step was to create an array, containing the timestamps (in the same format as dt_txt), for the dates and times I wanted to extract the data for.

Creating an array of timestamps

A new instance of the Date class was created, which returned today’s date. This was then used when creating Date objects for the following four days and then used to create the nextFourDaysarray:

const oneDay = 1000 * 60 * 60 * 24;
const today = new Date();
const todayPlus1 = new Date(today.getTime() + (oneDay));
const todayPlus2 = new Date(today.getTime() + (oneDay * 2));
const todayPlus3 = new Date(today.getTime() + (oneDay * 3));
const todayPlus4 = new Date(today.getTime() + (oneDay * 4));
const nextFourDays = [todayPlus1, todayPlus2, todayPlus3, todayPlus4]

Converting a Date object to a string

The above created an array of Date objects, where each date would be formatted like this:

2019-01-12T16:54:56.426Z

JSON.stringify()was used to convert it to a string. The .substring()method was used to extract the date part only:

let dateStrings = [];
nextFourDays.forEach(function(date) {
  const dateToString = JSON.stringify(date)
  dateStrings.push(dateToString.substring(1, 11))
});
----
dateStrings = ['2019-01-11', '2019-01-12', '2019-01-13', '2019-01-14']

Using nested forEach loops to combine data from two arrays

The next step was to create an array containing 16 strings. Each string would contain the date and time increment to extract. An array of time increments were created:

const times = ['00:00:00', '06:00:00', '12:00:00', '18:00:00']

Next, a forEach loop, iterating through the times array was nested within another forEach loop. This was iterating through the dateStrings array. Each time and date was pushed to the instance variable datesAndTimes

dateStrings.forEach((date) => {
  times.forEach((time) => {
    this.datesAndTimes.push(date + ' ' + time)
  })
})

Result:

this.datesAndTimes = [
        '2019-01-11 00:00:00',
        '2019-01-11 06:00:00',
        '2019-01-11 12:00:00',
        '2019-01-11 18:00:00',
        '2019-01-12 00:00:00',
        '2019-01-12 06:00:00',
        '2019-01-12 12:00:00',
        '2019-01-12 18:00:00',
        '2019-01-13 00:00:00',
        '2019-01-13 06:00:00',
        '2019-01-13 12:00:00',
        '2019-01-13 18:00:00',
        '2019-01-14 00:00:00',
        '2019-01-14 06:00:00',
        '2019-01-14 12:00:00',
        '2019-01-14 18:00:00'
]

Great! Now I had an array of timestamps formatted in the same way as dt_txt.

Resources: