如何从对象创建多维对象?一维对象转二维对象实现
解决方案:一维数组转嵌套对象
嘿,这事儿用JavaScript的reduce方法就能轻松搞定,正好适合这种逐步构建嵌套结构的场景。我直接给你写好代码,再一步步解释逻辑:
var data = [ {'id':1, 'price':'12', 'price_type':'abc', 'mode':1, 'year':1}, {'id':1, 'price':'22', 'price_type':'def', 'mode':1, 'year':1}, {'id':1, 'price':'15', 'price_type':'abc', 'mode':1, 'year':2}, {'id':1, 'price':'32', 'price_type':'def', 'mode':1, 'year':2}, {'id':1, 'price':'30', 'price_type':'abc', 'mode':1, 'year':3}, {'id':1, 'price':'35', 'price_type':'def', 'mode':1, 'year':3} ]; const result = data.reduce((acc, item) => { // 提取当前项的关键字段 const { mode, year, price_type, price } = item; // 把price转成数值(如果需要保留字符串可以去掉Number()) const priceValue = Number(price); // 生成对应的键名,比如abc → abc_price const priceKey = `${price_type}_price`; // 确保mode层存在,不存在就初始化空对象 if (!acc[mode]) { acc[mode] = {}; } // 确保year层存在,不存在就初始化空对象 if (!acc[mode][year]) { acc[mode][year] = {}; } // 给当前year对象赋值对应的价格 acc[mode][year][priceKey] = priceValue; return acc; }, {}); console.log(result);
输出结果
运行这段代码后,你会得到完全符合你要求的结构:
{ 1: { 1: { abc_price: 12, def_price: 22 }, 2: { abc_price: 15, def_price: 32 }, 3: { abc_price: 30, def_price: 35 } } }
逻辑拆解
- reduce方法:作为数组遍历的核心,
acc是我们正在构建的结果对象,每次迭代都会更新它 - 嵌套结构检查:每一层(mode → year)都先判断是否存在,不存在就创建空对象,避免报错
- 动态键名:用模板字符串把
price_type转成xxx_price的格式,完美匹配你要的键名 - 类型转换:把原数据里的字符串价格转成数值,要是你需要保留字符串,直接去掉
Number()就行
内容的提问来源于stack exchange,提问作者Ramesh Moorthy
相关产品推荐
相关产品推荐

