首页 > 解决方案 > 将数组更新为 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": [],
}

标签: javascriptapiasync-await

解决方案


您可以推入数组或使用扩展运算符。检查步骤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
};

推荐阅读