I have below const
const cartProducts = props.cartSlice;
whose output is below array
Array [
Object {
"cartQuantity": 3,
"product": "5f15d92ee520d44421ed8e9b",
},
Object {
"cartQuantity": 2,
"product": "5f15d964e520d44421ed8e9c",
},
Object {
"cartQuantity": 1,
"product": "62e5285f92b4fde9dc8a384c",
},
Object {
"cartQuantity": 4,
"product": "5f15d9b3e520d44421ed8e9d",
},
]
I am trying to write some code in reactjs to output separate arrays with the only the cartQuantity as below
Array [
3,
]
Array[
2,
]
Array[
1,
]
Array[
4,
]
The closest I have come to achieving this is below which is consolidating all the cartQuantity in a single array.
const quantity = cartProducts.map((item, i) => item.cartQuantity);
Array [
3,
2,
1,
4,
]
How can I modify my query to output separate arrays for each cartQuantity?
CodePudding user response:
You already mapped the initial array into an array of quantities, now if you want to get an array of arrays, with one quantity into each inner array, then it suffices to make the map
callback return an Array with such quantity.
const quantity = cartProducts.map((item, i) => [item.cartQuantity]);
Array [
Array [
3
],
Array[
2
],
Array[
1
],
Array[
4
]
]
CodePudding user response:
i may not have understood your question properly, but would
const quantity = cartProducts.map((item, i) => [ item.cartQuantity ]);
not do?
var cartProducts=[
{
"cartQuantity": 3,
"product": "5f15d92ee520d44421ed8e9b",
},
{
"cartQuantity": 2,
"product": "5f15d964e520d44421ed8e9c",
},
{
"cartQuantity": 1,
"product": "62e5285f92b4fde9dc8a384c",
},
{
"cartQuantity": 4,
"product": "5f15d9b3e520d44421ed8e9d",
},
]
const quantity = cartProducts.map((item, i) => [item.cartQuantity]);
console.log(quantity);