简体   繁体   中英

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

Here, I have taken an array named 'cardItem' inside another array 'cart'. Now, I want to map 'cardItem' array.

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

Based on below assumption of 'cart' being an array,

  • '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

one possible solution is presented in the code-snippet below:

 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 } /* <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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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