Object Map
Prompt
Design a function called objectMap that works similarly to JavaScript's Array map() method, but for objects.
Example
const obj = { a: 1, b: 2, c: 3 };
const mappedObj = objectMap(obj, (x) => x * 2);
console.log(mappedObj); // { a: 2, b: 4, c: 6 }
Playground
Solution
Explanation
The way I would solve this is by thinking about what an object map function should do - similar to how Array's map() works, but for objects.
First, we need to create a result object to store our mapped values.
const result = {};
Then, we need to iterate through all the keys in the source object. A for...in
loop is perfect for this.
for (const key in obj) {
// Code to handle each key
}
However, there's a catch with for...in
: it will also iterate over inherited properties from the prototype chain. To ensure we only map the object's own properties, we need to check. By using Object.hasOwn(obj, key)
, we can ensure we only process the object's own properties.
if (Object.hasOwn(obj, key)) {
// Only process the object's own properties
}
Now, for each key, we apply the callback function to transform the value and assign it to the same key in our result object.
result[key] = callback.call(obj, obj[key]);
Notice we're using callback.call(obj, obj[key])
instead of just callback(obj[key])
. This sets the this
context of the callback to be the original object, which is how Array's map() works - allowing the callback to access the original object if needed.
Finally, we return the new mapped object:
return result;
Put it all together, and we have a clean implementation of an object map function that transforms all values in an object while preserving the keys, similar to how Array's map() transforms all elements in an array.
This is a common pattern when working with objects in JavaScript - transform the data while maintaining the structure, just like we do with arrays using the built-in map() method.
Why hasOwn() over hasOwnProperty()
You will notice that I've used Object.hasOwn()
over Object.prototype.hasOwnProperty()
in the solution.
It is now recommended to use Object.hasOwn()
over Object.prototype.hasOwnProperty()
because it works for null-prototype objects and with objects that have overridden the inherited hasOwnProperty()
method.
While it is possible to workaround these problems by calling Object.prototype.hasOwnProperty()
on an external object, Object.hasOwn()
is more intuitive.
You can read more about it here Object.hasOwn().