0

I have the 1 dimension array called [cars] and values are added through an input box using React JS.

//initial array setup
const cars = [ ];
const [itemsList, setItemsList] = useState([ {brand: ""} ]);
 
//function called every time I add a new value
 
const carsUpdate = (e, index) => {     
    const list = [...itemsList];
    list[index]["brand"] = e.target.value;
    setItemsList(list);
  };

After adding 3 cars I get the following.

const cars = [
         { brand: “Fiat” },
         { brand: “Ford” },
         { brand: “Renault” }
];

The above works perfectly for 1 a dimension array type.

  Now, I’m trying to make it multi-dimension by adding an extra property [colors] to the array which contains another array   The idea is to get this type of result by adding colors separately and individually through other input boxes.

const cars = [
         { brand: “Fiat”, colors: [ “red”, “green” ] },
         { brand: “Ford”, colors: [ “blue”, “yellow” ] },
         { brand: “Renault”, colors: [ “red”, “white” ] },
]

  I have modified the following:

const [itemsList, setItemsList] = useState([ {brand: "", colors: [ ] } ])

but I’m struggling to modify the function carsUpdate to update the colors property with new values.

const carsUpdate = (e, index) => {     
    let list = [...itemsList];
    let innerList = [];
    innerList = list[index]["colors"]; 
    innerList.push(e.target.value);
    list[index][colors] = innerList;
    setItemsList(list);
  };
Butri
  • 339
  • 8
  • 22
  • In both of your examples you are mutating the inner object. Your first example should be `list[index] = {...list[index], brand: e.target.value};` see the flagged duplicate for more discussion. – pilchard Apr 29 '22 at 16:14
  • Does this answer your question? [How to update state with usestate in an array of objects?](https://stackoverflow.com/questions/62918710/how-to-update-state-with-usestate-in-an-array-of-objects) – pilchard Apr 29 '22 at 16:17
  • @pilchard not really since the example represent a single-dimensional array. In my first example I can modify easily values with a spread operator without a problem. The issue is when I need to access and modify the array values within a specific object of the overall array. – Butri Apr 29 '22 at 16:23
  • @jsN00b that is not part of the scope of this question. The challenge is how to modify (add/change/remove) values the colors property value without looping (i.e. .map) – Butri Apr 29 '22 at 17:13

0 Answers0