满分答案来了:const flattenObj = (obj, prefix = "") => { const result = {}; for (const [key, value] of Object.entries(obj)) { const newPrefix = prefix ? `${prefix}.${key}` : key; // 别使用typeof,会放过null if (value instanceof Object) { Object.assign(result, flattenObj(value, newPrefix)); } else if (![null, undefined].includes(value)) { result[newPrefix] = value; } } return result; }; const input = { a: "a", b: [1, { c: true }, [3]], d: { e: undefined, f: 3 }, g: null, }; const flattened = flattenObj(input); console.log(flattened);
点赞 评论

相关推荐

牛客网
牛客网在线编程
牛客网题解
牛客企业服务