I have an object:
myObject = { \'a\': 1, \'b\': 2, \'c\': 3 }
I am looking for a native method, similar to Array.prototype.map
I like the examples that use Object.fromEntries
such as this one, but still, they are not very easy to use. The answers that use Object.keys
and then look up the key
are actually doing multiple look-ups that may not be necessary.
I wished there was an Object.map
function, but we can create our own and call it objectMap
with the ability to modify both key
and value
:
Usage (JavaScript):
const myObject = { 'a': 1, 'b': 2, 'c': 3 };
// keep the key and modify the value
let obj = objectMap(myObject, val => val * 2);
// obj = { a: 2, b: 4, c: 6 }
// modify both key and value
obj = objectMap(myObject,
val => val * 2 + '',
key => (key + key).toUpperCase());
// obj = { AA: '2', BB: '4', CC: '6' }
Code (TypeScript):
interface Dictionary {
[key: string]: T;
}
function objectMap(
obj: Dictionary,
valSelector: (val: TValue, obj: Dictionary) => TResult,
keySelector?: (key: string, obj: Dictionary) => string,
ctx?: Dictionary
) {
const ret = {} as Dictionary;
for (const key of Object.keys(obj)) {
const retKey = keySelector
? keySelector.call(ctx || null, key, obj)
: key;
const retVal = valSelector.call(ctx || null, obj[key], obj);
ret[retKey] = retVal;
}
return ret;
}
If you are not using TypeScript then copy the above code in TypeScript Playground to get the JavaScript code.
Also, the reason I put keySelector
after valSelector
in the parameter list, is because it is optional.
* Some credit go to alexander-mills' answer.