typescript 预期为开始_ARRAY,但实际为BEGIN_OBJECT,如何将对象格式化为数组?

svmlkihl  于 2023-02-20  发布在  TypeScript
关注(0)|答案(1)|浏览(142)
{
    "workingHours":
        [
            {
                "date":"2023-02-01",
                "amount":3,
                "freigegeben":false
            }
        ]
}

当我在我的请求正文中发送这个时,我在标题中得到错误。我如何手动添加[ and ],使它成为一个数组?或者我如何解决这个问题?
这是我发送的请求:

public async saveWorkingHours(
    employeeId: string | null,
    workingHours: WorkingHours[]
  ): Promise<boolean> {

    var result = Object.entries(workingHours.map(wh => ({ ...wh, date: this.dateService.format(wh.date) })));
    try {
      await this.httpService.fetch(
        `${this.apiUrl}employees/${employeeId}/workingHours`,
        HttpMethod.PUT,
        {

          // This is my body, which starts with "{", instead of "[". That is the problem
          workingHours: workingHours.map(wh => ({ ...wh, date: this.dateService.format(wh.date) })),
        }
      );
      return true;
    } catch (e) {
      console.error(e);
      return false;
    }
  }

工作时间接口:

export interface WorkingHours {
  date: Date;
  amount: number;
  freigegeben: boolean;
}

这样做:

var convertedFormatData = [];

    var tempObj = {
      workingHours: workingHours.map((wh) => ({
        ...wh,
        date: this.dateService.format(wh.date),
      })),
    };
    convertedFormatData.push(tempObj);

我的输出如下所示:

{"convertedFormatData":[{"workingHours":[{"date":"2023-02-01","amount":3,"freigegeben":false},{ ...
snvhrwxg

snvhrwxg1#

一个月一个月是一个月一个月,一个月二个月是一个月三个月。
在这里,你从{开始,所以对于网站你似乎发送了一个对象,但是他在等待一个列表。要发送列表,你应该做:

[
   {
       "here": "is the json"
   }
]

对你来说,应该是这样的:

[
   {
      "workingHours":[
         {
            "date":"2023-02-01",
            "amount":3,
            "freigegeben":false
         }
      ]
   }
]

有几种方法可以将其设置为数组:

var test = {
  "workingHours":[
     {
        "date":"2023-02-01",
        "amount":3,
        "freigegeben":false
     }
  ]
};
console.log(test["workingHours"]);

相关问题