Save the quantity of each combination javascript

So I have 2 arrays. One contains the colors of a product and on contains sizes of a product.

Let’s say I have 2 colors (RED and BLUE), and 2 sizes (M and XL)

this right here is my jsx code:

{
    sizeArray.map((size) => colorArray.map((color) => <input onChange={(e) => setCurrentQuantity(e.target.value)} placeholder={size + "/" + color}></input>))
}

So the code above creates 4 inputs like this:

input 1: BLUE/M
input 2: BLUE/XL
input 3: RED/M
input 4: RED/XL

My question is how do I save all the inputs as an object?

>Solution :

You can store an object in the state, with one key-value pair per input.

const [quantity, setQuantity] = useState({});
// ...
sizeArray.map((size) => colorArray.map((color) => <input 
    onChange={(e) => setQuantity(prev => ({...prev, [size+'/'+color] : e.target.value})} 
    value={quantity[size+'/'+color]} placeholder={size + "/" + color}/>))

Leave a Reply