繁体   English   中英

如何计算每个对象的总价格 - react.js

[英]how to calculate total price in each object - react.js

我有这个结构

[
  [
    { 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 },
  ]
]

我需要计算每个数组的总价格,因此预期输出为:

405

198

336

我需要把这个值放在这个空的 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>

按顺序在空行中查看

在此处输入图像描述

每个 tr 依次为 405 然后 198 然后 336

这将为您提供预期的输出


 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>
          ))}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM