r/javascript • u/RelationNo8685 • Apr 07 '26
AskJS [AskJS] Do you prefer flattening API responses or keeping nested structures on the frontend?
[removed]
5
Upvotes
r/javascript • u/RelationNo8685 • Apr 07 '26
[removed]
11
u/vanilla_f Apr 07 '26
Nested makes everything clearer and self documenting
3
u/DustNearby2848 Apr 07 '26
It depends, usually just keep it in the format the backend has it as, unless there’s a good reason to change it. Last time I asked the backend team for a change was because I had to make a request per user in a table, that’s not cool; too many requests flying around and it needlessly complicated the front end and could potentially make the SLA much worse.
3
u/Careful-Falcon-36 Apr 08 '26
I usually don’t choose strictly "nested vs flattened" - I keep the API response as is and then shape it for the UI where needed.
A good pattern is
For example:
Or even better, centralize that in one place (adapter/service), so components don’t depend on API shape. Flattening everything globally can make updates harder and lose meaning, but keeping everything deeply nested can make UI code verbose. A thin transformation layer gives you the best of both. So don’t flatten the API itself - adapt it at the boundary.
2
u/jerquee Apr 07 '26
Are you doing API calls for each piece of information as opposed to getting an object containing everything?
2
u/blueshed60 Apr 07 '26
Store flat -calculate nested on the front end. Then updates are atoms and queries a dream.
1
u/Better-Avocado-8818 Apr 07 '26
Depends on the data I want in the front end. But I always put an adapter layer in between so that I have a single place to do data transforms and not leak the API type into my front end.
1
u/beavis07 Apr 07 '26
Data structures expressed by interfaces should describe the semantics of the data - not what makes the prettiest client code. That’s is a you problem 😂
1
u/Ronin-s_Spirit Apr 08 '26
I destructure things, especially if I want to store it in indexedDB and I don't need all the fields/nesting.
1
u/PalpitationOk839 Apr 08 '26
I prefer keeping it nested and creating a small mapping layer for UI.
Flattening everything can get messy long term.
Best is balance — structure + convenience.
1
u/Alive-Cake-3045 Apr 09 '26
I usually keep the nested structure as-is and only flatten where the UI actually needs it. It keeps things closer to the API and easier to maintain.
For repetitive access, I create small helper functions or a mapping layer instead of flattening everything. Full flattening can get messy and harder to track later.
So basically: nested by default, flatten selectively for convenience.
1
u/PalpitationOk839 Apr 09 '26
I prefer keeping it nested and creating a small transform layer for UI.
Flattening everything feels convenient at first but becomes harder to maintain. Balance works best here.