Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

82
Views
Appending object to array from a callback within a for loop

I am trying to push an object to an array, from within a for loop. The array appears empty in the end. When I console.log() the data I am attempting to push, it appears to be correct. The purpose of this code is to read JSON from a file, use the data from this to create an object and add this object to an array. The reason I am using an array and loop, is so that I can repeat this process for multiple files. Then I will save the final array with all the objects to a single file.

I am doing this in Node.JS

This is my code so far:

const fs = require('fs')

const create_data = async (number) => {
    let finished_data = []
    for(let i = 1; i <= number; i++){
        const path = "./generated_images/" + i + "/output.json"
        fs.readFile(path, 'utf8', function readFileCallback(err, data){
            if (err){
                console.log(err);
            } else {
                let obj = JSON.parse(data);
                finished_data.push({
                    id: obj.id,
                    img_url: obj.public_url,
                })
            }
        });
    }
    return finished_data
}

create_data(5).then(res => {
    console.log(res)
}) // I am just logging the data, eventually I will put an fs.writeFile() here, to write the array of objects to a file.
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!