DEV Community

Cover image for Mapping JavaScript Objects with Modern APIs
Laurin Quast
Laurin Quast

Posted on

Mapping JavaScript Objects with Modern APIs

Object.entries allows you to convert an object into an array structure:

console.log(Object.entries({prop1: 1, prop2: 2 }))
// [ ["prop1", 1], ["prop2", 2] ]

This method is part of the ECMAScript 2017 Spec and already heavily used by many developers (including me).

Until recently, there was no convenient method available to transform this structure back into an object.

Now, we finally have Object.fromEntries which allows constructing an object from the structure returned by Object.entries.

This makes it super convenient to map objects:

Implementation:

const mapValues = (input, mapper) =>
  Object.fromEntries(
    Object.entries(input).map(([key, value]) => [
      key,
      mapper(value, key, input)
    ])
  );

Usage example:

const input = {
  prop1: 1,
  prop2: 4,
};

const output = mapValues(input, value => value * 2);

expect(output).toEqual({
  prop1: 2,
  prop2: 8,
});

Support

Browser Support: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries#Browser_compatibility
Node Support: https://node.green/#ES2019-features--Object-fromEntries

Top comments (2)

Collapse
 
pallymore profile image
Yurui Zhang • Edited

Neat.

However one thing to note is that Object.entries ignores all symbol keys. If we want to support symbols:

const mapValues = (input, mapper) =>
  Object.fromEntries(
    [...Object.getOwnPropertyNames(input), ...Object.getOwnPropertySymbols(input)].map(key => [
        key,
        mapper(input[key], key, input)
    ])
  );

=>

const input = {
  foo: 1,
  [Symbol('bar')]: 4,
};

const output = mapValues(input, v => v * 2);

expect(output).toEqual({
  foo: 2,
  [Symbol('bar')]: 8,
});
Collapse
 
wiltel492019 profile image
Wiltel492019

Great job mapping and JavaScript methods of Operations. Modern API's. Gitter Done!!!
Wiltel49@gmail.com
AAS ITI MICHIGAN