如何实现JavaScript深层嵌套Object的扁平化(仅处理对象不展开数组)
JavaScript 嵌套对象扁平化实现方案
你可以通过递归遍历对象属性的方式实现需求,完整代码如下:
实现代码
// 判断是否为纯对象(排除数组、null等不需要展开的类型) const isPlainObject = (val) => typeof val === 'object' && val !== null && !Array.isArray(val) // 扁平化对象方法 const flattenObject = (sourceObj, prefix = '') => { const result = {} for (const key in sourceObj) { // 仅处理对象自身属性,跳过原型链继承的属性 if (sourceObj.hasOwnProperty(key)) { // 拼接当前层级的属性名 const currentKey = prefix ? `${prefix}/${key}` : key const currentValue = sourceObj[key] if (isPlainObject(currentValue)) { // 纯对象递归展开,将递归结果合并到当前结果中 Object.assign(result, flattenObject(currentValue, currentKey)) } else { // 非纯对象(基础类型、数组等)直接赋值保留原结构 result[currentKey] = currentValue } } } return result } // 测试用例 const obj = { name: "Allen", age: 26, address: { city: "city1", dist: "dist1", state: "state1" }, grandParent: { parent: { key1: "val1", key2: "val2", innerParent: { innerParentKey1: "innerParentVal1", innerParentKey2: "innerParentKey2", innerParentKey3: "innerParentVal3" } }, child: { childKey1: 'childVal1', childKey2: 'childVal2', childKey3: 'childVal3' } } } const obj2 = flattenObject(obj) console.log(obj2)
功能说明
- 仅展开纯对象类型的嵌套属性,数组、null、基础类型均保留原结构不展开
- 嵌套层级的属性名自动用
/拼接,根层级属性保持原名 - 自动过滤原型链继承属性,仅处理对象自身定义的属性
内容的提问来源于stack exchange,提问作者user15701022
相关产品推荐
相关产品推荐

