Skip to content
Advertisement

How to “flatten” a nested object array in React?

I have an object that contains multiple records in the format below:

JavaScript

For each of the multiple “names”, they have one and only one “units” array and within the “units” array, there will be one to many “unit_num” with an associated “street”. I’m trying to generate a flat table that looks like this.

name street rent lease
The Belvedere 1234 Main 900 2021-11-01
The Belvedere 1235 Main 875 2022-03-21
The Grayson 345 Maple 925 2023-10-31

Currently the code is this: The screen maps the “leases” object and calls the Lease component and passes a single “lease” entry.

JavaScript

And the Lease component prints it to the screen.

JavaScript

The challenge I’m facing is because I’m iterating the object, I can get each row to display, but they are not in a table, just individual rows on the screen.

But I can’t figure out how to pass the entire dataset object to the Lease component and within that component iterate and then populate and return the filled table, instead of passing the “names” individually.

Any suggestions?

Advertisement

Answer

The Lease component must return the rows and not the whole table, so you have to move the other components of the table to the parent component:

JavaScript

And the Lease component:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement