![](/img/trans.png)
[英]How to unshift or add to the beginning of arguments object in JavaScript
[英]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.