0

My API call gets a response like this

  {
  products: {
    product0: {
      id: 'F103_SURFACELAPTOP_15',
      quantity: 47,
      description: 'Surface Laptop 15 Zoll'
    },
     product1: {
      id: 'F101_MACBOOKPRO_13',
      quantity: 10,
      description: 'Macbook Pro 13 Zoll'
    }
  },
  salesOrderId: '9000002080'
}

It can contain 1 - n products. I'm trying to print the response in a table

This is what I got which is working but it will just show the first product. However I need to loop through products and show every product

  {value.map((item, i) =>
            <tr key={i}>
              <td>{i + 1}</td>
              <td>{item.salesOrderId}</td>
              <td>{item.products['product' + i].id}</td>
            </tr>
          )

This is how I tried to loop through it but with no success

   {value.map((item, i) =>
                <tr key={i}>
                  <td>{i + 1}</td>
                  <td>{item.salesOrderId}</td>
                  {item.products['product' + i].map((product, i) =>
                   <td key={i}> {product.i.id} </td>)}
                  <td>{item.products['product' + i].id}</td>
                </tr>
              )}
1
  • 7
    Whoever wrote that API should rethink the format of its output... Commented Mar 5, 2020 at 9:42

2 Answers 2

1

Because the value is Object not a Array

so use like this

{Object.values(value).map((item, i) =>

instead of

{value.map((item, i) =>

use loop on this format

{Object.values(value).map((item, i) =>
                <tr key={i}>
                  <td>{i + 1}</td>
                  <td>{item.salesOrderId}</td>
                  {Object.values(item.products).map((product,ind) =>
                   <td key={ind}> {product.id} </td>)}
                  <td>{item.products['product' + i].id}</td>
                </tr>
              )}
Sign up to request clarification or add additional context in comments.

Comments

0

To iterate through object attributes you can use Object.values(value) if you need only values, and Object.entries(value) if you need both: keys and values. Both this functions return arrays on which function map is available

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.