Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
    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}/>))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading