You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从对象创建多维对象?一维对象转二维对象实现

解决方案:一维数组转嵌套对象

嘿,这事儿用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:09:59