Looking for a way to dynamically update any field in an object? I have a method that aims to do just that. Whether it's the name, age, weight, or eye color of the object, I want to be able to pass in any field and have it updated accordingly.
Currently, I'm using the spread operator but encountering issues when trying to update a single field. There's an error stating that the fieldName doesn't exist within myObject. Is there a way to achieve this without resorting to a lengthy switch statement to check each field against the passed-in fieldName?
If you have any suggestions or ideas on how to accomplish this dynamically, I would greatly appreciate it. Thank you!
let myObject = {
name: 'John',
lastName: 'Smith',
age: 26,
weight: 200,
eyeColor: 'blue',
hairColor: 'blonde'
};
const handleUpdate = (fieldName: string, fieldValue: string | number) => {
if (fieldName in myObject) {
myObject = {...myObject, fieldName: fieldValue};
}
}
handleUpdate('name', 'Jack'); // Hoping for this call to change the name from 'John' to 'Jack'