【问题标题】:avoid callback hell with foreach method for formatting Json避免使用 foreach 方法格式化 Json 的回调地狱
【发布时间】:2022-01-06 09:59:54
【问题描述】:

我的代码有效,但我认为它效率不高,可能有更有效的方法。 我有一个 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."
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

}

我想用大写转换键对象,(我不想使用正则表达式):

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));
});

我不想用 foreach 方法制造回调地狱, 是一种更有效的方法吗?

谢谢

【问题讨论】:

标签: javascript node.js arrays


【解决方案1】:

递归更改对象属性:

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));
});

【讨论】:

    猜你喜欢
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-01
    相关资源
    最近更新 更多