I have a JavaScript object with the following structure:
{
id: 0,
content: "English Class",
date: "Dec 24th at 7:30pm",
completed: false,
}
I also have a function const editTask(id, content) that updates the content property in the aforementioned object:
const editTask = (id, content) => {
setTasks(tasks.map((task) =>
task.id === id ? { id: task.id, content: content, date: task.date, completed: task.completed } : task));
}
Is there a way in which I can avoid passing all the object properties to only upgrade the content property as well as just spreading the rest of the object?
CodePudding user response:
A common pattern is to combine the spread syntax with manually setting some properties:
const editTask = (id, content) => {
setTasks(tasks.map((task) =>
task.id === id ? { ...task, content } : task));
}
In the above example, the spread syntax sets all the properties of task, and the next line overrides the property content to the new value. It's important that the spread is before the content. If it were after, then the new value would be overridden by the spread.
