JS 对象扁平化

现在有一个对象:

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

要将其转化为:

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: ""
};

本质是维护一个新返回的对象,通过递归将key生成后,写入新对象中:

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);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。