mapObj
Same as Array.prototype.map, but for objects.
1./**2.* Same as Array.prototype.map, but for objects.3.**/4.const mapObj = <T, U>(5.obj: Record<string, T>,6.callback: (value: T, key: string, obj: Record<string, T>) => U,7.): Record<string, U> => {8.const result: Record<string, U> = {};9.10.// loop through each key in the object11.for (const key in obj) {12.// check if the key is a property of the object13.if (Object.prototype.hasOwnProperty.call(obj, key)) {14.result[key] = callback(obj[key], key, obj);15.}16.}17.18.return result;19.};20.21.export default mapObj;
1. Installtion
npx @jrtilak/lazykit add mapObj
2. Parameters
-
obj
(Record<string, T>
)
An object whose properties will be transformed. -
callback
((value: T, key: string, obj: Record<string, T>) => U
)
A function that is called for each property in the object. It receives the property value, the property key, and the entire object as arguments, returning the transformed value.
3. Returns
Record<string, U>
A new object with the same keys as the input object, but with values transformed by the callback function.
4. Example Usage
1. Basic Example
1.import mapObj from "@/helpers/mapObj";2.3.const originalObject = {4.name: "John",5.age: 30,6.city: "New York",7.};8.9.const transformedObject = mapObj(originalObject, (value, key) => {10.return typeof value === "number" ? value * 2 : value.toUpperCase();11.});12.13.console.log(transformedObject);14.// Output: { name: "JOHN", age: 60, city: "NEW YORK" }
2. With Nested Objects
1.import mapObj from "@/helpers/mapObj";2.3.const data = {4.alice: {5.age: 28,6.},7.los: {8.age: 50,9.},10.};11.12.const ages = mapObj(data, (value) => {13.return value.age;14.});15.16.console.log(ages);17.// Output: { alice: 28, los: 50 }