如何自定义JSON.stringify生成的JSON结构适配后端接口
实现方法
基础固定布局版本
如果layout字段是固定值(比如示例中的"regular"),直接构造目标结构后再序列化即可:
// 假设你的FilledCells数组为filledCells const filledCells: FilledCells[] = [ { floor: 0, coordinates: { x: 23, y: 1 }, type: "regular", seat: 2, group: "A" }, { floor: 0, coordinates: { x: 24, y: 1 }, type: "premium", seat: 1, group: "A" } ]; // 构造符合后端要求的结构 const requestPayload = { seatingConfiguration: [ { layout: "regular", // 这里可根据需求修改固定值 seats: filledCells } ] }; // 转换为JSON字符串 const jsonResult = JSON.stringify(requestPayload, null, 2);
执行后就能得到你需要的JSON结构。
按type分组版本(可选)
如果需要根据每个FilledCells对象的type字段自动分组生成不同的layout项,可以用数组的reduce方法处理:
const filledCells: FilledCells[] = [/* 你的数据 */]; // 按type分组生成seatingConfiguration数组 const groupedLayouts = filledCells.reduce((result, cell) => { // 处理type为undefined的情况,设为默认值 const layoutKey = cell.type ?? "default"; // 查找是否已有该layout的项 const existingItem = result.find(item => item.layout === layoutKey); if (existingItem) { existingItem.seats.push(cell); } else { result.push({ layout: layoutKey, seats: [cell] }); } return result; }, [] as { layout: string; seats: FilledCells[] }[]); // 构造最终请求结构 const requestPayload = { seatingConfiguration: groupedLayouts }; const jsonResult = JSON.stringify(requestPayload, null, 2);
这个版本会自动把同type的单元格归到同一个layout对应的seats数组中,适合需要动态分组的场景。
内容的提问来源于stack exchange,提问作者Presti
相关产品推荐
相关产品推荐

