简体   繁体   English

如何访问对象数组中的数组 React JS

[英]How to access array inside an array of Objects React JS

I'm working on react e-commerce project as a learning process and stuck in a situation where I have array of orders which contains multiple order objects, and inside order there's an array of OrderItems containing orderItem objects.我正在将反应电子商务项目作为一个学习过程进行工作,并且陷入了一种情况,即我有一个包含多个订单对象的订单数组,并且在订单内部有一个包含 orderItem 对象的 OrderItems 数组。

Here's the Array structure of two orders for reference.这里有两个命令的Array结构供参考。

myOrders: [
  {
    id: 1,
    order_items: [
      {
        prod_id: 1,
        name: 123,
        qty: 1,
      },
      {
        prod_id: 1,
        name: 123,
        qty: 1,
      },
    ],
  },

  {
    id: 2,
    order_items: [
      {
        prod_id: 4,
        name: "xyz",
        qty: 2,
      },
      {
        prod_id: 5,
        name: "abc",
        qty: 5,
      },
    ],
  },
];

How do I access order_items for all orders respectively?如何分别访问所有订单的 order_items? What I have tried so far is: Retrieved myOrders from reducer using useSelector, then destructured it to get order_items and used到目前为止我尝试过的是:使用 useSelector 从 reducer 中检索 myOrders,然后对其进行解构以获取 order_items 并使用

order_items.map() order_items.map()

function, but it throws an error saying function,但它会抛出一个错误说

Can't find map of undefined找不到未定义的 map

I'm learning React JS and not an expert yet.我正在学习 React JS,还不是专家。 Would really appreciate any kind of help from all the experts out there.非常感谢所有专家提供的任何帮助。

Thanks in advance提前致谢

You can try map function on myOrders array to retrieve order_items and the flat those into 1 single array您可以在 myOrders 数组上尝试map function 以检索 order_items 并将这些平面检索到 1 个单个数组中

 let myOrders = [ { id: 1, order_items: [ { prod_id: 1, name: '123', qty: 1 }, { prod_id: 1, name: '123', qty: 1 } ] }, { id: 2, order_items: [ { prod_id: 4, name: 'xyz', qty: 2 }, { prod_id: 5, name: 'abc', qty: 5 } ] } ]; let result = myOrders.map(i => i.order_items).flat(); console.log(result);

 const myOrders = [{id:1,order_items:[{prod_id:1,name:123,qty:1},{prod_id:1,name:123,qty:1}]},{id:2,order_items:[{prod_id:4,name:"xyz",qty:2},{prod_id:5,name:"abc",qty:5}]}]; const out = myOrders.reduce((a, b) => { a.push(...b.order_items); return a; }, []); console.log(out);

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

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