Home > Enterprise >  How to get a certain vaule from an array of Objects?
How to get a certain vaule from an array of Objects?

Time:09-04

I am trying to create a cart layout that displays the number of quantity of each product listed in React. The data of quantity is received from a redux state that comes like this:

[
{id: '630788107a0ce75d70be5350', quantity: 1, name: 'Nerea Sheppard', price: 176},
{id: '630788b388944200fdf6a6df', quantity: 1, name: 'Hollee Stanley', price: 423}
]

How to get the quantity each of the product?

   const card = useSelector((state) => state.addons.cart);
    
  addons.map((addon) => {
                    return (
    <Button
    onClick = {
            () => {
                dispatch(
                    REMOVE_FROM_CART({
                        id: addon._id,
                    })
                );
            }
        } >
        REMOVE ITEM
        </Button> 
        
        <p>
        // How to map and to get the quantity of each product from the card array 
        </p>
        <Button onClick = {
            () => {
                dispatch(
                    ADD_TO_CART({
                        id: addon._id,
                        name: addon.name,
                        price: addon.price_in_euro_per_day,
                    })
                );
            }
        } > 
        ADD ITEM
        </Button>

)})

CodePudding user response:

I guess the product-id is part of addon right? So I guess you want to find the product in the product-list which matches the addon._id? There are serveral ways to do that, a simple, but a not a optimised solution would be"

// How to map and to get the quantity of each product from the card array
{card.find((item) => item.id === addon._id).quantity} 

This will render the quantity directly into the html.

A second solution for quick access would be a hash-map and use the id as a key.

    const cardMap = card.reduce((map, item) => {
      map[item.id] = item;
      return map;
    }, {})
    
    
   // In the html part:
   
   <span>Quantity: {cardMap[addon._id].quantity}</span>

CodePudding user response:

card?.find((x) => x.id === addon._id) ?
    card?.find((x) => x.id === addon._id)
    .quantity :
    0
  • Related