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

177
Views
avoid callback hell with foreach method for formatting Json

My code works but i think it's not efficient, may be there is a more efficient way. I have a Json (data.json):

{
"Testaments":[
    {
        "Books":[
            {
                "Chapters":[
                    {
                        "Verses":[
                            {
                                "ID":2,
                                "Text":"Au commencement, Dieu créa les cieux et la terre."
                            },
                            {
                                "ID":2,
                                "Text":"La terre était informe et vide: il y avait des ténèbres à la surface de l'abîme, et l'esprit de Dieu se mouvait au-dessus des eaux."
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

}

i want transform key object in uppercase, (i don't want use regex):

const fs = require("fs");
const url = "./data.json";

var camalize = function camalize(str) {
    return str
        .toLowerCase()
        .replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => chr.toUpperCase());
};

fs.readFile(url, "utf8", (err, data) => {
    if (err) {
        console.error(err);
        return;
    }
    var obj = JSON.parse(data);
    changeName(obj);

    obj.testaments.forEach((elem, ind) => {
        changeName(elem);
        obj.testaments[ind].books.forEach((elem2, ind2) => {
            changeName(elem2);
            obj.testaments[ind].books[ind2].chapters.forEach((elem3, ind3) => {
                changeName(elem3);
                obj.testaments[ind].books[ind2].chapters[ind3].verses.forEach(
                    (elem4) => {
                        changeName(elem4);
                    }
                );
            });
        });
    });

    function changeName(obj) {
        for (const property in obj) {
            const newName = camalize(property);
            obj[newName] = obj[property];
            //console.log(typeof obj[newName]);
            delete obj[property];
        }
    }

    console.log("finish");

    fs.writeFileSync(`export/export.json`, JSON.stringify(obj, null, 2));
});

i doesn't want to make a callback hell with the foreach method, is the a more efficient method to do that ?

Thanks

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Change object properties recursively:

const fs = require("fs");
const url = "./data.json";

var camalize = function camalize(str) {
    return str
        .toLowerCase()
        .replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => chr.toUpperCase());
};

fs.readFile(url, "utf8", (err, data) => {
    if (err) {
        console.error(err);
        return;
    }
    var obj = JSON.parse(data);
    changeName(obj);

    function updateKey(obj, k) {
        const newName = camalize(k);
        obj[newName] = obj[k];
        delete obj[k];
        return newName;
    }


    function changeName(obj) {

        for (const k in obj) {

            if (typeof propValue === 'object' && obj[k] !== null && !Array.isArray(obj[k])) {

                changeName(obj[k]);

            } else if (Array.isArray(obj[k])) {

                const newName = updateKey(obj, k);

                obj[newName].forEach(el => {
                    changeName(el);
                });

            } else {

                const newName = updateKey(obj, k);
            }
        }
    }

    console.log("finish", JSON.stringify(obj, null, 2));

    fs.writeFileSync(`export/export.json`, JSON.stringify(obj, null, 2));
});
about 4 years ago · Juan Pablo Isaza Report
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!