Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

178
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda