title: ReactJS: Appending new object to an existing array with spread
body: <p>I have this array object to begin with</p>
  
  <pre><code>[
    {
      "name": "child",
      "pax": {}
    }
  ]
  </code></pre>
  
  <p>I wish to append new property which is an array. then I want to update/insert new object into that array. But something is wrong with my code</p>
  
  <pre><code>function App() {
    const [num, setNum] = useState(0);
    const [arr, setArr] = useState([
      {
        name: "child",
        pax: {}
      }
    ]);
  
    function appendage({ id, age }) {
      const toSaveArr = arr.map(o =&gt; {
        if (o.name === "child") {
          return {
            ...o,
            age: o.age
              ? o.age.map(o2 =&gt; {
                  if (o2.id === id) {
                    return {
                      id: o2.id,
                      age
                    };
                  }
                  console.log("o2", o2);
                  //something is wrong here
                  //why is it not adding new object?
                  return [
                    ...o2,
                    {
                      id,
                      age
                    }
                  ];
                })
              : [{ id, age }]
          };
        }
        return o;
      });
  
      setArr(toSaveArr);
    }
  
    return (
      &lt;div className="App"&gt;
        &lt;h1&gt;{num}&lt;/h1&gt;
        &lt;button
          onClick={() =&gt; {
            setNum(num + 1);
  
            appendage({
              id: num + 1,
              age: num + 1
            });
          }}
        &gt;
          add
        &lt;/button&gt;
        &lt;button&gt;update age where id equal to 2&lt;/button&gt;
        &lt;pre&gt;{JSON.stringify(arr, null, 2)}&lt;/pre&gt;
      &lt;/div&gt;
    );
  }
  </code></pre>
  
  <p><a href="https://codesandbox.io/s/pedantic-mclean-107q2" rel="nofollow noreferrer">https://codesandbox.io/s/pedantic-mclean-107q2</a></p>
  
  <p>I think I've used spread operator wrongly here.</p>