Home > Net >  How do I map an array of objects, that also have an array of objects inside it?
How do I map an array of objects, that also have an array of objects inside it?

Time:10-05

I am using TypeScript, and I am a bit of a newbie to it. I have an array like so, but the keys in 'orderBreakdownList' ("8" & "upward-trending") will be unknown to the app every time it loads.

{
  "userId": "00bdad66",
  "totalNumberOfOrders": 5,
  "totalNumberOfPackages": 54521,
  "totalNumberOfItems": 13,
  "totalNumberOfDeliveredOrders": 3,
  "totalPrice": 39409.0,
  "orderBreakdownList": [
    {
      "8": {
        "noOfItems": 1,
        "noOfPackages": 17160,
        "id": 8,
        "totalPrice": 3741.52,
        "orderItems": [
          {
            "upward-trending": {
              "tag": "upward-trending",
              "value": 6653.16,
              "price": 18798.89,
              "id": 76
            }
          }
        ]
      }
    }
  ]
}

I am trying to render out the 'orderBreakdownList' array that have objects inside it, and render the second array into a list. (Drop down table with single item data)

his is what I tried so far,

<div>
      {orderBreakdownList.map((items, index) => {
        return (
          <ol key={index}>
            {items.map((subItems, sIndex) => {
              return <li key={sIndex}> {subItems} </li>;
            })}
          </ol>
        );
     })}
</div>

But I am not getting this to work, nor get any data out of it. Maybe I need another map into it? I need some help, please.

CodePudding user response:

I'm assuming when you say "second array", you're referring to the orderItems inside the orderBreakdownList array. In that case, you would do something like this:

<div>
  {orderBreakdownList.map(orderBreakdown => (
    <ol>
      {Object.values(orderBreakdown).map(({ orderItems }) => (
        orderItems.map(item => (
          Object.values(item).map(({ tag, value, price, id }) => (
            <li key={id}>
              <div>{tag}</div>
              <div>{value}</div>
              <div>{price}</div>
            </li>
          )) 
        ))
      ))}
    </ol>
  ))}
</div>

The Object.values() takes the values of the object without having to explicitly define the keys - 8 and upward-trending in this case. If you want to know what the key is, replace Object.values() with Object.entries() which returns an array of tuples that contains the key and value of the object.

For example:

Object.entries(item).map(([key, value]) => {
 // Map nested item
})

CodePudding user response:

items is an object and you can get the sub items by retrieving the object keys. Then you can improve on that from there

<div>
      {orderBreakdownList.map((items, index) => {
       let keyName = Object.keys(items);
        return (
          <ol key={index}>
              <li> {items[keyName]} </li>;
          </ol>
        );
     })}
</div>
  • Related