/*
作者:德布罗煜
链接:https://www.nowcoder.com/discuss/860063?type=post&order=create&pos=&page=1&ncTraceId=&channel=-1&source_id=search_post_nctrack&subType=2&gio_id=4B11D26016AC8D56CAC57B6E316F3069-1646982291847
来源:牛客网
{
a: 'a',
b: [1, { c: true }, [3]],
d: { e: undefined, f: 3 },
g: null,
}
输入用例记不太清了,应该大致差不多吧
输出:
{
a: "a",
b[0]: 1,
b[1].c: true,
b[2][0]: 3,
d.f: 3
// null和undefined直接舍去
}
*/
const flat = (obj) => {
const ret = {}
for(let [key, value] of Object.entries(obj)) {
// 如果value是数组
if (typeof value === 'object' && value !== null) {
const temp = flat(value)
for (let [innerKey, innerVal] of Object.entries(temp)) {
if (!/^\d/.test(key) && !innerKey.startsWith('[')) {
ret[`${key}.${innerKey}`] = innerVal
} else if (/^\d/.test(key)) {
ret[`[${key}].${innerKey}`] = innerVal
} else {
ret[`${key}${innerKey}`] = innerVal
}
}
}
else if (value !== null && value !== undefined) {
if (/^\d/.test(key)) {
ret[`[${key}]`] = value
} else {
ret[key] = value
}
}
}
return ret
}
console.log(flat(({a:'a', b: [1,2], c:{d:3, g: undefined, h:[1,2,{k:'k', g: [1,2,3]}]}, e: null, f:undefined})))
console