0

I've an Array with Objects in this format: [{…}, {…}] How can i append another Object to it?

Im getting data from mongodb like [{value: '1', label: 'Tomato'}, {value: '2', label: 'Cheese'}]

and i wanna add {value: '3', label: 'onion'} to it with react select

const [defaultToppings, setDefaultToppings] = useState([]);

const [selectedToppings, setSelectedToppings] = useState([null]);

finalToppings = [...defaultToppings, ...selectedToppings] // Idk about this part

const handleSubmit = async () => {
    try {
      await axios.patch(
        `/api/products/${editProduct._id}`,
        {
          selectedToppings,
        },
        {
          headers: { Authorization: token },
        }
      );

      setSuccess(true);
    } catch (err) {
      err.response.data.msg && setErr(err.response.data.msg);
    }
  };

<Select
  key={defaultToppings}
  options={extraOptions}
  isMulti
  defaultValue={defaultToppings}
  onChange={setSelectedToppings}
  components={animatedComponents}
/>
zuZuu
  • 87
  • 1
  • 8
  • Does this answer your question? [Merge 2 arrays of objects](https://stackoverflow.com/questions/7146217/merge-2-arrays-of-objects) – isherwood Aug 18 '22 at 14:42
  • `finalToppings` is correct. You're basically just spreading the content of `defaultToppings` and `selectedToppings` – Gelo Chang Aug 18 '22 at 14:51
  • @isherwood so so... defaultTopping can be empty then i get this error: Uncaught TypeError: defaultToppings is not iterable but when its not empty it works kinda but the format is no longer [{…}, {…}] – zuZuu Aug 18 '22 at 14:58
  • Okay i edit more or less the original code... The problem is that onChange={setSelectedToppings} including only the newly added toppings and not the old one. so where i call this toppings im getting only the new toppings and the old toppings are "deleted / overwritten" thats why i wanna implement finaltoppings so defaultToppings (the old toppings) and selectedToppings (the new one) be one array with objects. – zuZuu Aug 18 '22 at 15:06
  • @isherwood do you know if there is a way to do it inside the axios.patch { selectedToppings, }, instead of slected topping do this: Array.prototype.push.apply(arr1,arr2); but atm i get the error: ',' expected – zuZuu Aug 18 '22 at 15:14

0 Answers0