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

如何自定义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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 02:00:19