繁体   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