JS 對(duì)象扁平化

現(xiàn)在有一個(gè)對(duì)象:

const obj = {
a: 1,
b: [1, 2, { c: true }],
c: { d: 1, e: 2, f: { g: 0 } },
d: null,
e: '',
};

要將其轉(zhuǎn)化為:

const result = {
a: 1,
b[0]: 1,
b[1]: 2,
b[2].c: true,
c.d: 1,
c.e: 2,
c.f.g: 0,
d: null,
e: ""
};

本質(zhì)是維護(hù)一個(gè)新返回的對(duì)象,通過遞歸將key生成后,寫入新對(duì)象中:

let res = {};
function flat(obj, type = "obj", prefix = "") {
    for (let key in obj) {
        let item = obj[key];
        let newKey = prefix ? (type === "obj" ? `${prefix}.${key}` : `${prefix}[${key}]`) : key;
        if (!(item instanceof Object)) {
            res[newKey] = item;
            continue;
        }
        if (Array.isArray(item)) {
            flat(item, "arr", newKey);
        } else if (item instanceof Object && !Array.isArray(item)) {
            flat(item, "obj", newKey);
        }
    }
}
flat(obj);
console.log("output:", res);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容