json 最小化对象以提高可读性

kiz8lqtg  于 2022-12-20  发布在  其他
关注(0)|答案(1)|浏览(122)

我有一个包含超过6000行的js对象。我想让它更可读。正如你所看到的对象结构下面有一些常见的东西在所有的环境中(“公用A”,“公用B”),有没有办法在另一个文件中管理通用内容,而在单独文件中管理可变内容(以便提高可读性),最后我们可以在主文件中链接这些文件以完成此结构。
对象结构

let obj = {
    "feature": {
        "dev":{
            "commonA": {},
            "commonB": {},
            "variableDev": {}
        },
        "stage":{
            "commonA": {},
            "commonB": {},
            "variableStage": {}
        },
        "local":{
            "commonA": {},
            "commonB": {},
            "variablelocal": {}
        },
        "prod":{
            "commonA": {},
            "commonB": {},
            "variableProd": {}
        }
    }
}

公共部分存在于单个文件中,可变部分存在于不同的文件中,我们可以通过某种方式将这些文件链接到主文件以完成原始结构。

euoag5mw

euoag5mw1#

尝试mdn docs中提到的Javascript proxy

const target = {
  message1: "hello",
  message2: "everyone",
};

const handler3 = {
  get(target, prop, receiver) {
    if (prop === "message2") {
      return "world";
    }
    return Reflect.get(...arguments);
  },
};

const proxy3 = new Proxy(target, handler3);

console.log(proxy3.message1); // hello
console.log(proxy3.message2); // world

对你来说我们可以这样做

const commanKeys = {
    commonA: "hello",
    commonB: "everyone",
    commonC: "ok",
    commonD: "fromCommanKeys"
};

const proxyHelper = {
    get(target, prop, receiver) {
        console.log(`%cparentKey: ${target.parentKey}`, "color: green");
        if (prop === "commonA") {
            // custom logic for A
            return "A";
        }
        else if (prop === "commonB") {
            // custom logic for B
            return "B";
        }
        else if (prop === "commonC") {
            // custom logic for C
            return "C";
        }
        else{
            return Reflect.get(...arguments)
        }
    }
};

let obj = {
    "feature": {
        "dev": {
            "utils": new Proxy({...commanKeys, parentKey: "dev"}, proxyHelper),
            "variableDev": {}
        },
        "stage": {
            "utils": new Proxy({...commanKeys, parentKey: "stage"}, proxyHelper),
            "variableStage": {}
        },
        "local": {
            "utils": new Proxy({...commanKeys, parentKey: "local"}, proxyHelper),
            "variablelocal": {}
        },
        "prod": {
            "utils": new Proxy({...commanKeys, parentKey: "prod"}, proxyHelper),
            "variableProd": {}
        }
    }
}

console.info(obj.feature.dev.utils.commonA);
console.info(obj.feature.dev.utils.commonB);
console.info(obj.feature.dev.utils.commonC);
console.info(obj.feature.dev.utils.commonD);

console.info(obj.feature.prod.utils.commonA);
console.info(obj.feature.prod.utils.commonB);
console.info(obj.feature.prod.utils.commonC);
console.info(obj.feature.prod.utils.commonD);

输出日志

parentKey: dev
A
parentKey: dev
B
parentKey: dev
C
parentKey: dev
fromCommanKeys
parentKey: prod
A
parentKey: prod
B
parentKey: prod
C
parentKey: prod
fromCommanKeys

相关问题