现在有一个对象:
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);