Sometimes I wish the same would exist for objects as well.
During a code review today I stumbled over this practical piece that applies
.map() to an object.
.map() over an object
In this example we're turning the
timestampSeconds on the
clientEvent into a timestamp with milliseconds by altering the key and value of this object property.
const clientEvent = Object.fromEntries( Object.entries(serverEvent).map(([key, value]) => key === "timestampSeconds" ? ["timestampMillis", secondsToMilliseconds(value)] : [key, value] ) );
The idea behind it is.
- Turn an object into an array with
Object.entries(). The object is now an array of arrays with key/value pairs (a couple). It looks like this:
- As your object is now an array, you can map over it and return the altered couples.
- Once all couples have been altered you can reconstruct the object with