I don't know shite about:
How to replace object key/value pair with .map
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.
▶️ Check out the Replit for the whole code example and run it to see it in action
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