JavaScript如何实现嵌套对象的flatten扁平化工具函数
对象扁平化flatten函数实现
实现思路
采用递归遍历的方式处理嵌套结构,核心逻辑如下:
- 遍历当前对象所有自有可枚举属性
- 若属性值为纯对象,将当前属性名与上层前缀拼接作为新前缀,递归处理该子对象
- 若属性值为非对象类型,直接将拼接好的完整属性名与对应值存入结果对象
代码实现
function flatten(obj, prefix = '') { const result = {} for (const key in obj) { // 跳过原型链继承的属性 if (!obj.hasOwnProperty(key)) continue // 拼接当前层级的完整属性名 const currentKey = prefix ? `${prefix}.${key}` : key const value = obj[key] // 校验是否为纯对象(排除null、数组、日期等类型) const isPlainObject = typeof value === 'object' && value !== null && Object.prototype.toString.call(value) === '[object Object]' if (isPlainObject) { // 递归处理子对象,合并结果 Object.assign(result, flatten(value, currentKey)) } else { // 非对象类型直接存入结果 result[currentKey] = value } } return result }
示例验证
const myMap = { 'a': 5, 'b': 6, 'c': { 'f': 9, 'g': { 'm': 17, 'n': 3 } } } console.log(flatten(myMap)) // 输出结果: // { // a: 5, // b: 6, // 'c.f': 9, // 'c.g.m': 17, // 'c.g.n': 3 // }
内容的提问来源于stack exchange,提问作者Joji
相关产品推荐
相关产品推荐

