The Array.map()
function allows to to map each value of an array to a new value. If you want to map an object - its keys, values or both - you can use Object.entries()
and Object.fromEntries()
to convert the object to an array and back to an object.
The Object.entries()
function expects an object and returns an array with key-value pairs in the form of an array [key, value]
. Then you can use Array.map()
to map the keys and/or values.
The transformed array can be converted back to an object by using Object.fromEntries()
.
// 1. Create an object
const obj = { one: 1, two: 2, three: 3 };
// 2. Convert the object to an array of key-value pairs
const entries = Object.entries(obj);
// [ ["one", 1], ["two", 2], ["three", 3] ]
// 3. Map the array to new keys or values
const transformed = entries.map(([key, value]) => {
// Change the value to a string and add leading zeros
return [key, value.toString().padStart(3, "0")];
});
// 4. Convert the transformed array back to an object
const finalResult = Object.fromEntries(transformed);
// { one: "001", two: "002", three: "003" }