I am trying to structure my input data but I am not getting what I want. The input data is dynamic which will come from the database.
Suppose I have this below JSX. I want to get the value from the user that he selected and also the product title which is exist on the products
. Note that list data is dynamic I have hardcoded the values.
{products.map((product, i) => {
return (
<li onChange={(e) => getItemValues(e.target, product)}>
<label className="container_radio">
Medium size
<span> $5.00</span>
<input
type="radio"
value={5.00}
name={'Medium size'}
/>
<span className="checkmark"></span>
</label>
</li>
<li onChange={(e) => getItemValues(e.target, product)}>
<label className="container_radio">
Extra Largse size
<span> $8.00</span>
<input
type="radio"
value={8.00}
name={'Extra Largse size'}
/>
<span className="checkmark"></span>
</label>
</li>
);
})}
Here is the function to get the data and save it in a state
const getItemValues = (e, product) => {
setItemDetail((prevValue) => [
...prevValue,
{ [e.name]: e.value },
{ title: product.title },
]);
};
The above code output is:
[0: {Extra Largse size: '8.0'}
1: {Medium size: '5.00'}
2: {title: 'Barnes Chapman'}]
I want something like this
[{title: 'Barnes Chapman', options:{extra large size: '8.0',Medium size: '5.00' } }]
CodePudding user response:
To do this you need to find the product details from the ItemDetail
array. Try something like below.
const getItemValues = (e, product) => {
setItemDetail((prevValue) => {
const existingProduct = prevValue.find(item => item.title === product.title);
if(existingProduct) {
existingProduct.options = {...existingProduct.options, [e.name]: e.value}
return prevValue;
} else { /* new entry */
return [...prevValue, {title: product.title, options:{[e.name]: e.value}}]
}
});
};