0

I'm trying to clone an object with the spread operator like others are saying but when I make changes to the cloned object the original gets modified too, why does it happen?

Array that I'm getting from the API

{
    "fdcId": 173944,
    "description": "Bananas, raw",
    "scientificName": "Musa acuminata Colla",
    "foodNutrients": [
        {
            "nutrientId": 1186,
            "nutrientName": "Folic acid",
            "nutrientNumber": "431",
            "unitName": "UG",
            "derivationCode": "Z",
            "derivationDescription": "Assumed zero (Insignificant amount or not naturally occurring in a food, such as fiber in meat)",
            "derivationId": 68,
            "value": 0,
            "foodNutrientSourceId": 5,
            "foodNutrientSourceCode": "7",
            "foodNutrientSourceDescription": "Assumed zero",
            "rank": 7000,
            "indentLevel": 0,
            "foodNutrientId": 1817868,
            "dataPoints": 0
        },
        {
            "nutrientId": 1110,
            "nutrientName": "Vitamin D (D2 + D3), International Units",
            "nutrientNumber": "324",
            "unitName": "IU",
            "derivationCode": "Z",
            "derivationDescription": "Assumed zero (Insignificant amount or not naturally occurring in a food, such as fiber in meat)",
            "derivationId": 68,
            "value": 0,
            "foodNutrientSourceId": 5,
            "foodNutrientSourceCode": "7",
            "foodNutrientSourceDescription": "Assumed zero",
            "rank": 8650,
            "indentLevel": 1,
            "foodNutrientId": 1817869,
            "dataPoints": 0
        },

Cloning it

<input onKeyDown={(e) => {
  if (e.key == "Enter") {
   let editingFood = {...selectedFood}
   editingFood.foodNutrients.map((e) => {e.value = 10})
   console.log(editingFood);
   console.log(selectedFood);
  }
}} type="text" placeholder='Type the food weight (g)' className={styles.search_bar}/>
jeansvf
  • 13
  • 5

0 Answers0