DEV Community

Jack
Jack

Posted on

2 1

Object.entries is awesome

Somebody asks you to loop through the properties of an object, most of us will reach for Object.keys right?

Object.keys(obj).forEach(key => {
  const value = obj[key];
  // do something
})
Enter fullscreen mode Exit fullscreen mode

Somebody asks you to map the properties of an object to other values. Object.keys to the rescue again right?

const newObj = {};
Object.keys(obj).forEach(key => {
  newObj[key] = fn(obj[key]);
});
Enter fullscreen mode Exit fullscreen mode

Wait, no reduce? That's so 2018! Let's be needlessly functional:

const newObj = Object.keys(obj).reduce((acc, key) => {
  return {
    ...acc,
    [key]: fn(obj[key])
}, {});
Enter fullscreen mode Exit fullscreen mode

Nice!

Thing is, Object.entries and Object.fromEntries are now widely supported. You can now achieve the same thing like this:

const newObj = Object.fromEntries(
  Object.entries(obj).map([key, value]) => {
    return [key, fn(value)];
  })
);
Enter fullscreen mode Exit fullscreen mode

It's also trivial to just make a utility function that combines the fromEntries and entries calls:

const mapEntries = (obj, fn) => Object.fromEntries(
  Object.entries(obj).map(fn)
);
Enter fullscreen mode Exit fullscreen mode

you could then write the above like this:

const newObj = mapEntries(obj, ([key, value]) => [key, fn(value)]);
Enter fullscreen mode Exit fullscreen mode

I love how simple this is, and you can do so much stuff that's always been a bit of a pain before.

Want to transform keys?

const newObj = mapEntries(obj, [key, value]) => [fn(key), value]);
Enter fullscreen mode Exit fullscreen mode

Want to invert an object?

const inverted = mapEntries(obj, ([key, value]) => [value, key]);
Enter fullscreen mode Exit fullscreen mode

Want to filter properties out of an object?

const filtered = Object.fromEntries(
  Object.entries(obj).filter(([ , value]) => {
    return value === true;
  })
);
Enter fullscreen mode Exit fullscreen mode

Object.entries is awesome, have a play with it.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay