Spread operator in objects

Hi, in this post we are going to use the spread operator (…) in objects.

We can use the spread operator to keep or maintain old values and add new values, for example we have this object called “cars

  const [cars, setCars] = useState({
    id: "1",
    brand: "BMW",
    year: "20211",
    color: "black",
  });

This object looks like this:

Then in a button onClick method we can add more values to “cars” object like this:

   <button
          onClick={() =>
            setCars({
              ...cars,
              id: "2",
              brand: "Honda",
            })
          }
        >
          Add Car
        </button>

Here in the ...cars object we are keeping the original object data (color and year) and then adding new data into the id and brand properties.

Note: remember that we can access to the object properties like this using the array format [propertyName]:

By Cristina Rojas