

新闻资讯
行业动态本文介绍在 laravel + ajax 场景下,将多层嵌套的会话数据(如购物车商品)中各子对象的值提取并合并为单个扁平对象的方法,支持纯 javascript(es6)高效实现,无需后端改造。
在 Laravel 中通过 session()->get('cart.products') 获取的购物车数据常以多组命名键(如 data1、data2)包裹若干带随机 ID 键名的商品对象,而前端 Ajax 接收后往往需要将其“去键扁平化”——即忽略外层分组键与内层 ID 键的结构,仅保留所有商品对象本身,并合并到一个统一对象中(注意:不是数组,而是键值对集合,如示例中最终结果仍是 {1234543: {...}, 3453234: {...}, ...} 形式)。
这并非转换为数组([]),而是将多个对象的自有属性(即内层商品对象)合并进一个顶层对象。正确做法是使用 JavaScript 原生方法 Object.values() 提取所有子对象,再用展开运算符 ... 配合 Object.assign() 实现无冲突合并:
// 假设 Ajax 成功回调中收到的响应数据为 response
const response = {
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 mergedProducts = Object.assign({}, ...Object.values(response));
console.lo
g(mergedProducts);
// 输出:
// {
// 1234543: { id: 1, title: 'Product Title1', ... },
// 3453234: { id: 2, title: 'Product Title2', ... },
// 4564234: { id: 3, title: 'Product Title3', ... },
// 4643345: { id: 4, title: 'Product Title4', ... },
// 8679673: { id: 5, title: 'Product Title5', ... },
// 2344565: { id: 6, title: 'Product Title6', ... }
// }⚠️ 注意事项:
总结:面对 Laravel 会话中多级键名嵌套的商品数据,推荐采用 Object.assign({}, ...Object.values(response)) 一行式合并,语义清晰、性能优异、零依赖,是现代前端处理此类结构化数据的标准实践。