例. 观察题干,要点在于递归的抽取出值,构造对应的属性名(个人认为是此题难点)。
// 实现一个 flatten 函数,实现如下的转换功能
const obj = {
a: 1,
b: [1, 2, { c: true }],
c: { e: 2, f: 3 },
g: null, // null和undefined忽略
};
// 转化为扁平化之后的对象
let objRes = {
a: 1,
"b[0]": 1,
"b[1]": 2,
"b[2].c": true,
"c.e": 2,
"c.f": 3
};
题解. 解题前先弄清题干,再动手!
function flat(obj) {
let res = {};
function flatten(obj, newKey) {
if(! obj){
return; // 忽略undefined、null
}
if (Array.isArray(obj)) {
for (let key in obj) {
flatten(obj[key], `${newKey}[${key}]`); // 数组和对象的属性名有一些区别所以分开判断
}
} else if (obj instanceof Object) {
for (let key in obj) {
// 构造对象属性名,若前缀为空则不加 '.'
flatten(obj[key], newKey?`${newKey}.${key}`:key);
}
} else {
res[newKey] = obj; // 非数组和对象就保存在结果中
}
}
flatten(obj, ''); // 执行扁平化操作,否则返回的res为空对象
return res;
}
console.log(flat(obj));