Having trouble looping through an array of objects containing images in Javascript?

I am currently facing challenges with iterating through an array of objects that contain images. The array appears empty when logged in the console, but upon inspecting it in the console, I can see all the objects along with their iteration numbers. I have been unable to find a clear solution online on how to properly format the array for iteration using a 'for in' loop in Vue.js. I have included the code below with comments providing more context than my description.

        const frameImage = [
        {
            url: 'http://www.realmadryt.pl/fotki/_up/newsy/lukamodric_165.png'
        },
        {
            url: 'http://www.realmadryt.pl/fotki/_up/newsy/florentinoperez_11.jpg'
        },
        {
            url: 'http://www.realmadryt.pl/fotki/_up/newsy/ramosbarkinsta1.jpg'
        },
        {
            url: 'http://www.realmadryt.pl/fotki/_up/newsy/lukamodric_165.png'
        },
        {
            url: 'http://www.realmadryt.pl/fotki/_up/newsy/florentinoperez_11.jpg'
        },
        {
            url: 'http://www.realmadryt.pl/fotki/_up/newsy/ramosbarkinsta1.jpg'
        },
    ];

    let createdImages = [];

    frameImage.forEach(item => {
        const image = new Image();
        image.src = item.url;
        image.onload = () => {
            // set image only when it is loaded
            createdImages.push({
                image,
                width: image.width,
                height: image.height,
                x: 0,
                y: 0,
                draggable: true
            });
        };
    });
    console.log(createdImages)


    // no output
    createdImages.forEach(item => {
        console.log(item)
    });

    //still no output
    for(img in createdImages) {
        console.log(img);
    }

    //length shown as 0?
    console.log(createdImages.length)

Also available on jsFiddle: LINK

Answer №1

To optimize the loading of images, one approach is to map the array of URLs to an array of promises that resolve once the image has fully loaded. Afterward, using Promise.all, you can efficiently wait for all images to load and resolve. Here's a sample implementation:

Promise.all(frameImage.map(({ url }) => new Promise((resolve, reject) => {
  const image = new Image()
  image.onload = () => resolve({
    image,
    width: image.width,
    height: image.height,
    x: 0,
    y: 0,
    draggable: true
  })
  image.onerror = reject
  image.src = src
}))).then(createdImages => {
  // Perform operations on loaded images here
}).catch(err => {
  console.error('Could not load all images', err)
})

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

HTML comment without the presence of javascript

Is it possible to use different expressions besides checking for the browser or version of IE in order to display/hide content? For example: <!--[if 1 == 0]--> This should be hidden <!--[endif]--> I am considering this option because I send o ...

Problems with Ajax functionality in CodePen

Currently working on the Wikipedia Viewer project for freeCodeCamp. I'm encountering an issue with the ajax function as nothing is being logged in the console upon click. The code snippet in question is provided below. Appreciate any help or insight o ...

Exploring the functionality of window.matchmedia in React while incorporating Typescript

Recently, I have been working on implementing a dark mode toggle switch in React Typescript. In the past, I successfully built one using plain JavaScript along with useState and window.matchmedia('(prefers-color-scheme dark)').matches. However, w ...

Managing state changes in React can be a complex task, but

As a newcomer to React, I am currently working on creating an icon menu. However, I am facing an issue with my handleChange function not functioning as expected. While the icon Menu and possibleValues menu are visible, I am unable to select any of the op ...

Leveraging Ajax in Django to communicate with the backend and showcase the outcome

I need assistance with implementing ajax functionality to send user input to a Django backend for text processing, and then display the results. However, due to my limited experience with ajax, I'm struggling to figure out where I'm going wrong. ...

Dynamic data retrieval with the power of JavaScript and AJAX

When attempting to send data using AJAX in PHP, I encountered an issue with my jQuery click function on a button that sends data only when the quantity is greater than 1. The error arises because PHP does not recognize the variables 'name' and &a ...

Creating a Full Page Background Image That Fits Perfectly Without Resizing or Cropping

Can someone help me achieve the same effect as the website linked below, where the background image fades instead of being a slideshow? The image should be 100% in width and height without any cropping. I have managed to set this up with the codes provided ...

Reset checkboxes in Material UI data grid

Currently, I am immersed in a React Js project that involves various tabs, each containing a unique data grid table with rows featuring checkboxes. Issue: Whenever I select a row from Table 1 and navigate to Tab 2 before returning to Tab 1, the checkboxes ...

Having trouble exporting an object from a different JavaScript file in Node.js

I have been attempting to make the getCurrentSongData function retrieve the songdata object passed in from the scraper. However, I am encountering the following output: ******************TESTING**************** c:\Users\(PATH TO PROJECT FOLDER)& ...

Combining Various Data Types in a Flexible List

I'm looking for a way to dynamically add rows to a table. Right now, I have the input type on the server (whether it's int, bool, string, etc), but I want to know how to implement a field accept combobox. Here is the code in cshtml: <tr ng-r ...

The concept of Theme.breakpoints does not exist in MUI React, there is

I keep running into the same error where theme.breakpoints is undefined when I try to use theme.breakpoints.up in my code. The versions of the dependencies I am currently using are: "@emotion/react": "^11.9.0", "@emotion/styled&quo ...

Thorax.js bower installation issue

After following the instructions in this guide: https://github.com/walmartlabs/thorax-seed/blob/master/README.md, I ran into an unexpected issue on my Windows machine. When running npm start It seems like bower is doing a lot of work (presumably loading ...

Safari on iOS 11.4 ignoring the 'touch-action: manipulation' property

I ran into an issue while developing a React web app that I want to work seamlessly across different platforms. My goal was to allow users to interact with a div element by double-clicking on desktop and double-tapping on mobile devices. However, when tes ...

Encountering issues when trying to combine Sequelize with TypeScript

As I attempted to transition my NodeJs application to TypeScript, I encountered issues with Sequelize. Upon attempting to implement the code from a website, an error occurred: This expression is not constructable. Type 'typeof import("/home/de ...

The Express.js feature "app.use() mandates the use of middleware functions"

Currently, I am delving into learning Express.js 4 and Node, but I seem to have hit a roadblock with an error that has me stumped. I'm attempting to utilize the node-sass package to compile my sass code; however, I've encountered obstacles in ge ...

Using AngularJS in conjunction with Ruby on Rails is causing compatibility issues

Trying to implement Angular with Ruby on Rails is presenting some challenges. While simple expressions like 1+1 work fine, binding a number or string to a scope seems to be causing issues. I am looking for suggestions on how to resolve this problem. app. ...

Displaying HTML content fetched from a database in Vue

I am currently developing a blog application that utilizes Vue.js for the frontend and Node.js for the backend. For the content creation part of the blog, I have implemented a rich text editor called vue2-editor on the frontend. The goal is to store this ...

How can I set up an additional "alert" for each form when making an AJAX request?

let retrieveLoginPasswords = function (retrieveForgottenPasswords, checkLoginStatus) { $(document).ready(function () { $('#login,#lostpasswordform,#register').submit(function (e) { e.preventDefault(); $.ajax({ type: &quo ...

Tips for choosing a week on a calendar with JavaScript

Here is the code for my calendar: <script> $(document).ready(function() { var events = <?php echo json_encode($data) ?>; $('#calendar').fullCalendar({ header: { left: 'prev,next', center: &apos ...

Using JavaScript to replace a radio button with the term "selected"

I am currently in the process of developing a quiz that is powered by jQuery and possibly JSON, with data being stored in a database. Everything is functioning correctly at this point, but I would like to enhance the user interface by hiding the radio butt ...