js 对象扁平化函数
几年前面试的时候,有一道对象扁平化的笔试题目没答好,现在看来挺简单,可见当时基本功欠缺...
- 题目输入示例:
const input = {
a: {
b: 1,
c: 2,
d: { e: 5 },
},
b: [1, 3, { a: 2, b: 3 }],
c: 3,
};
- 题目输出如下:
{
'a.b': 1,
'a.c': 2,
'a.d.e': 5,
'b[0]': 1,
'b[1]': 3,
'b[2].a': 2,
'b[2].b': 3,
c: 3
}
- 直接上答案:
// 简单判断是否基础类型
const isPrimitive = val => typeof val !== 'object';
const getKey = (key, pre, isArr) =>
isArr ? `${pre}[${key}]` : `${pre ? pre + '.' : ''}${key}`;
const result = {}
function flat(obj, prefix = '') {
const iterator = (value, key, isArr) => {
const newKey = getKey(key, prefix, isArr);
if (isPrimitive(value)) {
result[newKey] = value;
} else {
flat(value, newKey);
}
};
if (Array.isArray(obj)) {
obj.forEach((value, key) => iterator(value, key, true));
} else if (typeof obj === 'object' && obj !== null) {
Object.keys(obj).forEach(key => iterator(obj[key], key));
}
}
flat(input);
console.log(result);