JavaScript数组转嵌套对象:如何实现扁平数组到嵌套结构的转换
JavaScript扁平数组转嵌套对象解决方案
我来帮你搞定这个嵌套对象转换的问题!你需要把一组包含键值对的扁平数组,转换成层层嵌套的对象结构,对吧?先明确下你的需求:
输入扁平数组:
const start = [{'a':'b'}, {'b':'c'}, {'c':'d'}, {'d':'e'}]期望输出嵌套对象:
const end = {a: {b: {c: { d: {} } } } }
下面给你两种简洁高效的解决方案,同时分析下你现有代码的问题:
方案一:循环构建(推荐)
先把数组转换成键值对映射表,这样能快速查找每个键对应的下一个键,再通过循环逐步构建嵌套结构:
const start = [{'b':'c'}, {'a':'b'}, {'c':'d'}, {'d':'e'}]; // 第一步:将扁平数组转为键值映射表,提升查找效率 const keyMap = start.reduce((map, item) => { const currentKey = Object.keys(item)[0]; map[currentKey] = item[currentKey]; return map; }, {}); // 第二步:从起始键开始循环构建嵌套对象 function buildNestedObject(startKey) { const result = {}; let currentObj = result; let currentKey = startKey; while (keyMap[currentKey]) { const nextKey = keyMap[currentKey]; // 在当前层级创建键并赋值为空对象,然后将指针移到这个新对象上 currentObj[currentKey] = {}; currentObj = currentObj[currentKey]; currentKey = nextKey; } return result; } // 从'a'开始构建嵌套对象 const end = buildNestedObject('a'); console.log(end); // 输出 {a: {b: {c: {d: {}}}}}
方案二:递归构建
如果你更喜欢递归写法,这种方式逻辑更直观简洁:
const start = [{'b':'c'}, {'a':'b'}, {'c':'d'}, {'d':'e'}]; // 先转成键值映射表 const keyMap = start.reduce((map, item) => { const [currentKey] = Object.keys(item); map[currentKey] = item[currentKey]; return map; }, {}); // 递归函数:传入起始键,返回对应的嵌套对象 function buildRecursive(startKey) { // 如果当前键没有后续关联键,返回空对象 if (!keyMap[startKey]) return {}; // 否则返回 { 当前键: 递归处理下一个键的结果 } return { [startKey]: buildRecursive(keyMap[startKey]) }; } const end = buildRecursive('a'); console.log(end); // 输出目标嵌套对象
你的现有代码问题分析
你的思路方向是对的,但有几个关键卡点:
- 递归逻辑错误:
convert函数里直接把temp赋值给end[key],会导致每次递归都在根对象上新增属性,无法实现层级嵌套。 - 查找效率低下:
getObj每次用find遍历数组,不如先转成映射表实现O(1)快速查找。 - 多余的
findKey函数:不需要额外查找键,通过映射表就能直接获取每个键对应的下一个关联键。
内容的提问来源于stack exchange,提问作者prgrmr
相关产品推荐
相关产品推荐

