DEV Community

Discussion on: Is reduce() bad?

Collapse
mpuckett profile image
Michael Puckett • Edited on

I’ve started using .map with Object.fromEntries in places I would have used reduce but it does make it look even more cryptic.

 const increment = obj => Object.fromEntries(Object.entries(obj).map(([ key, value ]) => [ key, value + 1 ]))

increment({ x: 1, y: 2 })
// { x: 2, y: 3 }
Enter fullscreen mode Exit fullscreen mode
Collapse
jasterix profile image
Jasterix Author

Haha it does only because of the chaining to keep everything on one line. I think if you split it up as Ken does, it's a ton more effective

Collapse
kenbellows profile image
Ken Bellows

I definitely have mixed feelings about this paradigm. I absolutely see the value in quickly mapping from one object to another, but I agree that Object.fromEntries(Object.entries(obj).map(...)) is not the most readable thing.

On the one hand, I sort of expect that it will become a paradigm that is so ubiquitous that everyone will just get used to seeing it and immediately recognize what it's doing, so readability will become less of a problem over time. But on the other hand, if it is going to become that common of an operation, I sort of wish there was a built-in method for it, something like Object.mapEntries(([key, val]) => [key, val+1]), that just did it all in one go.

All that said, it does become a little more readable when split onto a few lines:

const increment = obj => Object.fromEntries(
    Object.entries(obj)
        .map(([ key, value ]) => [ key, value + 1 ])
)

Collapse
mpuckett profile image
Michael Puckett • Edited on

We need Object.mapEntries then I think!