I have a helper function that I want to accept a few parameters and update an object. The idea is to cal the function and pass the key I want to access (dynamic) and the new value for that key.
export function updateObject(id, key, value, arrayOfObjects) {
const arr = [...arrayOfObjects];
const index = arrayOfObjects.findIndex((x) => x.id === id);
arr[index].key = value;
return arr;
}
The issue is arr[index].key = value;
isn't accessing the key
value I'm passing as a parameter. It's just assuming that arr[index]
has a key called key
.
This doesn't help as I want this to be able to edit any key for all objects based on what key we pass as a parameter when calling the function. For example:
updateObject(2, "name", "John")
updateObject(2, "age", "32")
This should be able to use the same function rather than hardcoding different functions for different keys. Is there a better way to do this? If I have the right idea, how can allow the key (parameter) to work dynamically?