skip to Main Content
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


  1. const preState = {
      a: [1, "x", 4]
    }
    const arr = [2, 3];
    
    const nextState = {
      a: preState.a.flatMap(v => v === 'x' ? arr : v)
    }
    
    console.log('nextState: ', nextState)
    Login or Signup to reply.
  2. Use the spread opeartor ... to destructure obj.a. The below code replaces x with the contents of arr. Check this link for details on how spread operator works: https://www.geeksforgeeks.org/javascript-spread-operator/

    const [obj, setObj] = useState({a:[1, "x", 4]});
    const arr = [2, 3];
    const [one,two,...rest]=obj.a;
    setObj({a:[one,...arr,...rest]});
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search