贝利信息

如何将嵌套对象中各层级的键值对合并为一个扁平化对象

日期:2026-01-13 00:00 / 作者:花韻仙語

本文介绍在 laravel + ajax 场景下,将多组带随机键名的对象(如购物车商品数据)合并为单一对象的方法,重点提供 javascript 端高效解决方案,并说明 laravel 端可选优化方式。

在 Laravel 应用中,当购物车数据以关联数组形式(如 session()->get('cart.products'))通过 JSON 响应返回给前端时,常出现类似如下结构:外层为 data1、data2 等分组键,内层则以商品 ID 为键、商品对象为值。但前端通常需要统一处理所有商品——即忽略分组层级,将所有商品条目“扁平化”聚合到一个对象中,保持原始键名(如 1234543、4643345)不变,仅合并值

这并非数组拼接([]),而是对象合并({}):目标是得到一个单层对象,其所有属性均为商品 ID → 商品对象的映射关系。

✅ 推荐方案(前端 JavaScript,简洁高效):

// 假设 Ajax 成功回调中 receivedData 即服务端返回的响应对象
const receivedData = {
  data1: {
    '1234543': { id: 1, title: 'Product Title1', description: 'Product Descrition1' },
    '3453234': { id: 2, title: 'Product Title2', description: 'Product Descrition2' },
    '4564234': { id: 3, title: 'Product Title3', description: 'Product Descrition3' }
  },
  data2: {
    '4643345': { id: 4, title: 'Product Title4', description: 'Product Descrition4' },
    '8679673': { id: 5, title: 'Product Title5', description: 'Product Descrition5' },
    '2344565': { id: 6, title: 'Product Title6', description: 'Product Descrition6' }
  }
};

// 一行代码完成合并:提取所有子对象 → 展开为参数 → 合并为单个对象
const flattenedProducts = Object.assign({}, ...Object.values(receivedData));
console.log(flattenedProducts);
// 输出:
// {
//   '1234543': { id: 1, ... },
//   '3453234': { id: 2, ... },
//   '4564234': { id: 3, ... },
//   '4643345': { id: 4, ... },
//   '8679673': { id: 5, ... },
//   '2344565': { id: 6, ... }
// }

? 原理说明:

⚠️ 注意事项:

? 总结:
面对多层级、键名动态的商品数据结构,优先在前端用 Object.assign(...Object.values()) 实现零成本扁平化——语义清晰、性能优异、无需额外依赖。该模式同样适用于其他类似场景,如权限菜单合并、多区域配置聚合等。