Home > other >  how to calculate total price in each object - react.js
how to calculate total price in each object - react.js

Time:06-12

I have this structure

[
  [
    { title: 'McRoyale', price: 70, count:5, totalPrice: 350 },
    { title: 'Big Mac', price: 55, count:1, totalPrice: 55 },
  ],
  [
    { title: 'Double Big Tasty', price: 99, count:2, totalPrice: 198 },
  ],
  [
    { title: 'Grand Chicken Premier', price: 72, count:3, totalPrice: 216 },
    { title: 'Spicy Chicken Fillet', price: 60, count:2, totalPrice: 120 },
  ]
]

and I need to calculate the total price for each array so the expected output to be:

405

198

336

and I need to put this values in this empty td

<table className='table'>
        <thead>
          <tr>
            <th scope='col'>Items</th>
            <th scope='col'>Total Items Price</th>
          </tr>
        </thead>
        <tbody>
          {cardItems.map((items) => (
            <tr>
              <td>
                {items.map((item) => (
                  <>
                    <b className='mc-red'>{item.title}</b> Item Price:{' '}
                    {item.price} LE, Item Count: {item.count}, Item Total Price:{' '}
                    {item.totalPrice} LE
                    <br />
                  </>
                ))}
              </td>
              <td>{}</td>
            </tr>
          ))}
        </tbody>
      </table>

to be viewed here in the empty rows by order

enter image description here

405 then 198 then 336 in each tr in order

CodePudding user response:

This will give you the expected output


 const calcPrice = (item) => {
    return item.reduce((accumulator, object) => {
      return accumulator   object.totalPrice;
    }, 0);
  };


   {cardItems.map((items) => (
            <tr>
              <td>
                {items.map((item) => (
                  <>
                    <b className="mc-red">{item.title}</b> Item Price:{" "}
                    {item.price} LE, Item Count: {item.count}, Item Total Price:{" "}
                    {item.totalPrice} LE
                    <br />
                  </>
                ))}
              </td>
              <td>{calcPrice(items)}</td>
            </tr>
          ))}
  • Related