0

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?

Yehuda
  • 27
  • 15
  • 5
    arr[index][key] – cmgchess Mar 20 '23 at 16:47
  • Interesting. Why exactly does this work? Just wondering the reasons – Yehuda Mar 20 '23 at 16:48
  • 1
    with square brackets you can do dynamic stuff. with the dot it tries to access exact field. also u need square bracket if u have weird field names like fields containing spaces – cmgchess Mar 20 '23 at 16:49
  • 1
    `a.key` is accessing the property called `key` on object `a`, whereas `a[key]` is accessing the property whose name is the value of the variable `key`. See https://stackoverflow.com/questions/4244896/accessing-an-object-property-with-a-dynamically-computed-name – evolutionxbox Mar 20 '23 at 16:50
  • 1
    https://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets – cmgchess Mar 20 '23 at 16:51

1 Answers1

0

You can also use find and get the object in which you intend to change the key

export function updateObject(id, key, value, arrayOfObjects) {
  const arr = arrayOfObjects.find((x) => x.id === id);
  arr[key] = value;
  return arr;
}
brk
  • 48,835
  • 10
  • 56
  • 78
  • I'm setting a react state though with this return so don't i need to deconstruct and reconstruct the array? Or I can just edit the array coming in and return that edited array. – Yehuda Mar 20 '23 at 16:53