javascript - 将数组更新为 mockAPI
问题描述
我有这样一个对象mockAPI
{
"id": "1",
"name": "qqq",
"email": "qqq",
"password": "qqq",
"tasks": [],
"gettingTasks": [],
}
我想在数组中添加"tasks"
几个 "ids"
const createTaskUser = (id, idTask) => {
const user = usersGateway.fetchUser(id) here i query the user and get the object as above
const newUser = {
...user,
tasks:idTask
}
usersGateway.updateUser(id, newUser) is a function that accepts a user id that needs to be updated and a new dataset
}
如果我运行此函数,它将覆盖这些值,但我需要添加数据。
几次调用后,数组应如下所示:
{
"id": "1",
"name": "qqq",
"email": "qqq",
"password": "qqq",
"tasks": [1,4,75,3,2],
"gettingTasks": [],
}
解决方案
您可以推入数组或使用扩展运算符。检查步骤tasks: [...user.tasks, idTask]
const createTaskUser = (id, idTask) => {
const user = usersGateway.fetchUser(id); // here i query the user and get the object as above
const newUser = {
...user,
tasks: [...user.tasks, idTask]
};
usersGateway.updateUser(id, newUser); //is a function that accepts a user id that needs to be updated and a new dataset
};
// 如果允许推送
const createTaskUser = (id, idTask) => {
const user = usersGateway.fetchUser(id); // here i query the user and get the object as above
user.tasks.push(idTask)
usersGateway.updateUser(id, user); //is a function that accepts a user id that needs to be updated and a new dataset
};
推荐阅读
- asp.net-core - 如何在asp.net core razor中将选择的单选按钮值发送到模态
- racket - 在 Racket 中动态加载模块
- java - 如何从java中的contect-type“application/pdf”中提取文本内容
- python - 无法转换参数
- docusignapi - 使用 PHP 中的标记字段通过电子邮件发送 DocuSign PDF
- c++ - Nlohmann Json“array”和“array_t”之间的区别
- android - 在景观中使用 2fragment 更新回收视图
- c - 链接期间数组多个定义错误
- java - 如何显示我在数组元素中输入的内容
- python - 如何根据具有新名称的多列旋转熊猫数据框?