Nested loops in JavaScript can be combined with promises to efficiently handle

I am facing a challenge in looping through an array that contains another array as one of the parameters. My goal is to iterate through this nested array according to specific requirements, and then execute a function once the parent loop is finished. Can anyone help me identify where I might be going wrong with this task?

const schedule = {}
data.schedule.forEach(item => {
  let date = moment(item.date).format('YYYY-MM-DD')
  let eventList = []
  item.events.forEach(event => {
    let start = moment(event.start).format('h:mm A')
    let end = moment(event.end).format('h:mm A')
    let time = `${start} - ${end}`
    eventList.push({time: time, name: event.name})
  })
  return Promise.all(eventList).then(list => {
    console.log('list', list)
    schedule[`${date}`] = list
  })
})

// my current issue:

Promise.all(schedule).then(list => {
  console.log('schedule:', list)
})

// but this throws an error:
// TypeError: (var)[Symbol.iterator] is not a function
// at Function.all (native)

The desired output should resemble the following object:

{'2017-12-06': [
  {time: '9am - 10am', name: 'Jackson Home'},
  {time: '11AM - 3PM', name: 'Jackson Home'},
  {time: '3PM - 8PM', name: 'Jackson Home'}
]}

Answer №1

Well, it appears I've made a foolish mistake and require a refreshment pause:

const agenda = {}

  data.agenda.forEach(item => {
    let date = moment(item.date).format('YYYY-MM-DD')
    let eventList = []
    agenda[`${date}`] = item.events.map(event => {
      let start = moment(event.start).format('h:mm A')
      let end = moment(event.end).format('h:mm A')
      let time = `${start} - ${end}`
      return {time: time, name: event.name}
    })
  })

  console.log('agenda:', agenda)

Answer №2

As mentioned by @charlietfl, the existing code is not utilizing asynchronous functionality, hence removing the need for Promise.

The revised code snippet achieves the desired outcome:

const newSchedule = {}
data.schedule.forEach(item => {
  let date = moment(item.date).format('YYYY-MM-DD')
  let eventList = []
  item.events.forEach(event => {
    let start = moment(event.start).format('h:mm A')
    let end = moment(event.end).format('h:mm A')
    let time = `${start} - ${end}`
    eventList.push({time: time, name: event.name})
  })

  newSchedule[`${date}`] = eventList
})

When provided with this input:

{
    schedule: [
        {
            date: '2017-01-01',
            events: [
                {
                    name: 'test',
                    start: '2017-01-01 10:00:00',
                    end: '2017-01-01 11:00:00'
                }
            ]
        }
    ]
}

...the output will be structured like below:

{
    "2017-01-01": [
        {
            "time": "10:00 AM - 11:00 AM",
            "name": "test"
        }
    ]
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to generate an extensive table with HTML and AngularJS?

I am looking to implement an expandable table feature where a single header with a plus icon can be clicked to reveal the child rows beneath it. Currently, I have been able to achieve this functionality. However, I am facing an issue where the child rows ...

What is the best way to retrieve a specific value from a JSON file using a numerical identifier?

Imagine a scenario where there is a JSON file structured like this: { "data": [ { "id": "1", "name": "name1" }, { "id": "2", "name": "name2" } ] } If you know the ...

Incorporate JQuery into your NodeJS project by leveraging the existing minified file

Can we integrate JQuery into Node.js and make JQuery AJAX calls without altering the syntax by using a pre-downloaded minimized JQuery file? To clarify, I have the minified file and wish to incorporate it into Node.js in this manner: var jquery = require( ...

Keep an eye on the syncing progress of pouchdb replication

What is the best way to alert the user if there is a loss of Internet connection or if the server goes offline, causing live sync to stop? var localdb = new PouchDB('localdb'); var remotedb = new PouchDB('http://localhost:5984/xyz&a ...

What is the solution for - Uncaught TypeError: Cannot access the property 'scrollHeight' of an undefined element?

Could someone kindly assist me in resolving an issue? I recently encountered a problem with a script I have been using on the Chrome console. This script has been working perfectly fine for the past few days. However, today when I ran it, I started receiv ...

Can Ajax be utilized to invoke an internal function within a web application?

Brand new to PHP, this is a whole new world for me. Currently, I am attempting to dynamically update a drop down list from 1-10 based on the selection of a previous drop down list. The initial drop down list allows you to choose tables numbered 1-35, whil ...

Changing a password on Firebase using Angular 5

I am in the process of developing a settings feature for user accounts on an application I've been working on. One key functionality I want to include is the ability for users to update their password directly from the account settings page. To enable ...

Ways to merge two arrays into one in React JS

Here are two arrays presented below: const arrayA = { 0: { id: XXXXXXX, name: "test" }, 1: { id: YYYYYYY, name: "example" } } const arrayB = { 0: { id: XXXXXXX, category: "sea", } 1: { id: YYYYY ...

Issues with Markdown text editor code, table, and list functionalities are causing malfunction

Looking for a solution to use markdown editor for writing blog posts? If you're facing issues with code blocks, list items, tables, etc., not working correctly after publishing your markdown-based posts, while other elements like images, links, and bo ...

How can I implement jQuery Ajax to handle multiple elements on a single webpage?

I recently created a page where users can add items to their "favorites" list using the following JavaScript code: $(function(){ $('.doit-01234').click(function (e) { e.preventDefault(); $.ajax({ url: "https://www.domain. ...

What's the best way to save data from an HTML input field into a JavaScript array?

Can someone help me with storing a value from an HTML input field into a JavaScript array after a button click, and then displaying that array data on the screen? Here is the HTML code I am currently working with: <!DOCTYPE HTML> <html> < ...

Retrieving, storing, and implementing the classes of child elements directly from an array using jQuery

With the help of jQuery, you can retrieve child elements of the #parent element that have the class .west. In this case, we are not interested in fetching the content of these child elements but instead their class names. For example: <div id="parent" ...

Compact looped slideshow

Currently in the process of designing a website and looking to incorporate a unique photo gallery feature. The concept is as follows: The photo gallery will be displayed in a rectangular/box shape. There are a total of 10 photos, with only 7 initially vis ...

What are the steps to convert a canvas element, using an image provided by ImageService as a background, into a downloadable image?

I've been working on an app that allows users to upload an image, draw on it, and save the result. To achieve this functionality, I'm using a canvas element with the uploaded image as its background. The image is retrieved through ImageService. B ...

Are Bootstrap Input groups inconsistent?

Hey there! I've been working on the sign-in example, but I seem to have hit a roadblock. In my local setup, the top image is what I see in my browser after running the code, while the desired layout that I found on the Bootstrap site is the one below ...

The second instance of a React Paginate on the same page remains static and does not trigger a

Having a bit of trouble with using react-paginate for pagination - I have two instances on the same page (one at the top and one at the bottom). When a new prop is received, only the top instance gets re-rendered. The code seems to be working fine as all ...

Button in HTML not functioning as expected

I have 3 different files that are crucial for my webpage to function properly: index.html: <html> <head> </head> <body> <h1>Webpage</h1> <p id = "text">Hello world!</p> <button oncl ...

Sending a parameter from a click event to a function

Struggling with a jQuery and AJAX issue all night. I am new to both and trying to implement something similar to this example. I have an edit button with the ID stored in a data-ID attribute. Here's an example of what my button looks like: <butto ...

Showing a JSON file in an HTML page

I've been attempting to showcase a local JSON file on an HTML page. I stumbled upon some information online, but it's causing me quite a bit of confusion. Here is the JSON file I have: { "activities": [ { "name": "C:&bs ...

Struggling to place buttons below each row in a Bootstrap DataTable, unfortunately, they are only appearing under a specific column rather than the entire row

I have developed a system for managing event expenses that includes an option for multiple installments of a single payment for each event. My goal is to display these installments when a user hovers over an event in the table, with each row representing a ...