const [obj, setObj] = useState({a:[1, "x", 4]});
const arr = [2, 3];
After I fire the setObj function, I want whatever’s in the second index of the "a" array that is "x" to be replaced with whatever’s inside the arr, so the output should be:
{a:[1, 2, 3, 4]}
Also the contents of the arr are not predetermined and can change before the function is fired.
I tried copying the obj and modifying the array using the splice method, but it didn’t work because the setObj function is bound to an onChange event and is fired repeatedly.
2
Answers
Use the spread opeartor
...
to destructureobj.a
. The below code replaces x with the contents ofarr
. Check this link for details on how spread operator works: https://www.geeksforgeeks.org/javascript-spread-operator/