簡體   English   中英

將 object 附加/添加/取消移動到 api 響應的開頭

[英]append/add/unshift an object to the beginning of an response from an api

當從 api 調用返回數據時,我想向從 api 調用返回的數據添加額外的數據。 到目前為止,我已經從后端獲得了數據,但我想將 append 額外數據添加到從后端返回的數據的開頭。 我不確定該怎么做。

export const getMessageTemplates = (): Promise<
  ReadonlyArray<MessageTemplate>
> =>
  fetch(REACT_APP_BACKEND_LOCATION + "/api/template", {
    method: "get",
    credentials: REACT_APP_BACKEND_LOCATION === "." ? "same-origin" : "include",
    headers: {
      Accept: "application/json",
    },
  }).then(res=>res.json())
  .then(data=>data.unshift(
    {templateId: " ", category: "", title: "blank message", defaultTemplate:false}
    )).then(data=> data);
    

data.unshift返回更新data數組的長度。 只需像這樣更改該實現即可顯式返回data :-

export const getMessageTemplates = (): Promise<
  ReadonlyArray<MessageTemplate>
> =>
  fetch(REACT_APP_BACKEND_LOCATION + "/api/template", {
    method: "get",
    credentials: REACT_APP_BACKEND_LOCATION === "." ? "same-origin" : "include",
    headers: {
      Accept: "application/json",
    },
  })
  .then(res=>res.json())
  .then(data=>
    {data.unshift(
    {templateId: " ", category: "", title: "blank message", defaultTemplate:false})
    return data;
    }).then((data)=>// do whatever with data);

盡管您可以避免在最后使用額外的then鏈接和data回調,而只是在您使用unshift的前一個中使用它。

試試這個方法:

fetch('https://reqres.in/api/users')
    .then(res => res.json())
    .then(res => {
        res.data.unshift({templateId: " ", category: "", title: "blank message", defaultTemplate:false});
        console.log(res.data) // new updated array
    });

Lakshya 的解決方案非常適合您的需求,是一個很好的答案。

如果您想在不使用unshift()的情況下獲得與您正在尋找的相同結果,您還可以使用擴展運算符將新數組返回到data內聯而無需 return 語句:

export const getMessageTemplates = (): Promise<
  ReadonlyArray<MessageTemplate>
> =>
  fetch(REACT_APP_BACKEND_LOCATION + "/api/template", {
      method: "get",
      credentials: REACT_APP_BACKEND_LOCATION === "." ? "same-origin" : "include",
      headers: {
        Accept: "application/json",
      },
    })
    .then(res => res.json())
    .then(data => [{ templateId: " ", category: "", title: "blank message", defaultTemplate: false }, ...data])
    .then((data) => /* your logic here */);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM