Skip to content
Advertisement

How to simplify function which returns an object?

I have a function which returns an object but I don’t like that I gotta declare it first and then do forEach method

JavaScript

I think there should be something like this

JavaScript

But for some reason, it doesn’t work.

PS: In this part —

JavaScript

— I’m trying to create a key with a name separated by a dot (I don’t like that, but that’s what back-end wants me to)

Input :

JavaScript

Output :

JavaScript

I also would like any suggestions on how to write more readable code

Advertisement

Answer

Did you consider using reduce?

JavaScript

You can also use Object.fromEntries, map and flatMap should do the job:

JavaScript

First, you build an array for each subentry, for each subentry, you flatten the array you got into an array of key/value, then with Object.fromEntries, you make a new object!

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