New using Axios. I need help with the body formatting of my Axios post in React Js
My code:
body: JSON.stringify(
{
quote_timestamp: timestamp,
number_of_products: state.length,
} &&
state.map((product) => ({
quote_timestamp: timestamp,
number_of_products: state.length,
products: {
cat_Number: product.cat,
product_Name: product.Name,
},
}))
)
At the moment it is printing the data, as it maps each product like this:
body [
{
quote_timestamp: '7/24/2022, 11:25:27 PM',
number_of_products: 3,
products: {
cat: 'AB1',
Name: 'Alpha'
}
},
{
quote_timestamp: '7/24/2022, 11:25:27 PM',
number_of_products: 3,
products: {
cat: 'AB2',
Name: 'Beta'
}
},
{
quote_timestamp: '7/24/2022, 11:25:27 PM',
number_of_products: 3,
products: {
cat: 'AB3',
Name: 'Gamma'
}
}
]
However, I would like the format to be such that the timestamp and number of products are printed once and then maps through all selected products. Like this below:
body[ {
quote_timestamp: '7/24/2022, 11:25:27 PM',
number_of_products: 3,
products: {
{ cat: 'AB1', Name:'Alpha' },
{ cat: 'AB2' Name:'Beta' }.
{ cat: 'AB3' Name:'Gamma' }
}
}
CodePudding user response:
To get close to what you want, you would simply do this
JSON.stringify({
quote_timestamp: timestamp,
number_of_products: state.length,
total_price: total,
products: state.map((product) => ({
cat_Number: product.Cat_Number,
product_Name: product.Product_Name,
Price: product.mockPrice,
})),
})
Hope that helps
edit: oops, typo