-2

I have the following object with an array of objects inside that also contains arrays.

I want to create an HTML table where I display the cars per brand. I want to put the same brand under each other if there are multiple models where only the first get shown, the rest of the models should be shown with an collapsible row.

In the table below the second Audi model should be hidden and only be displayed with an click on the row.

<table>
<tbody>
<tr>
<td>Brand</td>
<td>Model</td>
<td>Price</td>
</tr>
<tr>
<td>BMW</td>
<td>X</td>
<td>200</td>
</tr>
<tr>
<td>Audi</td>
<td>Z</td>
<td>150</td>
</tr>
<tr>
<td>Audi</td>
<td>T</td>
<td>100</td>
</tr>
</tbody>
</table>

This is the data I work with:

var result object:

{
            "BMW": [
                {
                    "id": 0,
                    "title": "BMW",
                    "model": "X",
                    "price": "200"
                }
            ],
            "Audi": [
                {
                    "id": 0,
                    "title": "Audi",
                    "model": "Z",
                    "price": "150"
                },
                {
                    "id": 0,
                    "title": "Audi",
                    "model": "T",
                    "price": "100"
                }
            ]
        }

How can I do this?

1 Answers1

-1

You can use Object.keys to get the identifiers for the top-level object, then just .forEach to iterate through

Here's a working demo, with your data:

const data = {"BMW":[{"id":0,"title":"BMW","model":"X","price":"200"}],"Audi":[{"id":0,"title":"Audi","model":"Z","price":"150"},{"id":0,"title":"Audi","model":"T","price":"100"}]};

Object.keys(data).forEach((carMake) => {
  data[carMake].forEach((model) => {
    console.log(model);
  });
});
Alicia Sykes
  • 5,997
  • 7
  • 36
  • 64