如何在 React JS 中映射来自两个嵌套数组的数据?

How to map data from two nested arrays in react js?

在这里,我在另一个数组“cart”中使用了一个名为“cardItem”的数组。现在,我想映射“cardItem”数组。

enter image description here

 {
                        cart.cardItem?.map(item =><tr >
                            
                            <td></td>
                            <td> <img src={item.image} alt="" className='cart-image order-image' /> <br />
                            <small>{item.name}</small>
                            </td>
                            <td>{item.price}</td>
                            <td>{item.cartQuantity}</td>
                            <td>{item.cartQuantity*item.price}</td>
                        </tr>

                            )   
                        }

基于以下假设 'cart' 是一个数组,

  • 'cart' array has multiple elements each of which is an object
  • cartItem (within each cart-array element) is an array
  • cartItem-array has elements that have name, image, price props

下面的代码片段中提供了一种可能的解决方案:

const cart = [{
    cartQuantity: 1,
    cartItem: [{
      name: 'Item Name 01',
      image: 'someImage.png',
      price: 25
    }, {
      name: 'Item Name 101',
      image: 'someImage.png',
      price: 12
    }]
  },
  {
    cartQuantity: 5,
    cartItem: [{
      name: 'Item Name 02',
      image: 'someImage.png',
      price: 10
    }]
  },
  {
    cartQuantity: 1,
    cartItem: [{
      name: 'Item Name 03',
      image: 'someImage.png',
      price: 50
    }, {
      name: 'Item Name 101',
      image: 'someImage.png',
      price: 18
    }]
  }
];
// 'cart' array has multiple elements each of which is an object
// cartItem (within each cart-array element) is an array
// cartItem-array has elements that have name, image, price props

const getAllItems = (cart = []) => 
  (cart?.map(
    cartObj => cartObj?.cartItem?.map(
      item => ({
        image: item.image,
        name: item.name,
        price: item.price,
        cartQuantity: cartObj.cartQuantity,
        quantityTimesPrice: cartObj.cartQuantity * item.price ?? 0
      }
  /* <tr>
    <td></td>
    <td>
      <img src={item.image} alt="" className='cart-image order-image' />
      <br />
      <small>{item.name}</small>
    </td>
    <td>{item.price}</td>
    <td>{cartObj.cartQuantity}</td>
    <td>{cartObj.cartQuantity*item.price}</td>
  </tr> */
))));
// the above will return an array-of-array (of objects). If required, use .flat(), to get a simple array of objects instead.
// for simplicity in reviewing the results, have returned an object instead of JSX/HTML.
console.log(getAllItems(cart));
console.log('as a flat array: ', getAllItems(cart).flat());

说明

  • 首先,遍历'cart'数组
  • 中的每个元素
  • 在上面的代码片段中,每个 'cart' 数组元素都使用 'cartObj'
  • 进行处理
  • 对于购物车数组中的每个元素,遍历 'cartItem' 数组
  • 现在,对于每个 'cartItem'(在上面的代码片段中简称为 'item'),收集名称、图片、价格
  • 计算 cartQuantity(使用 'cartObj' 的外部迭代)和价格(来自 'item')的乘积

注意: ?. and ?? are the optional-chaining and Nullish coalescing 个运算符,分别。