How about a one-liner in JS ES10 / ES2019 ?
Making use of Object.entries()
and Object.fromEntries()
:
let newObj = Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, v * v]));
The same thing written as a function:
function objMap(obj, func) {
return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, func(v)]));
}
// To square each value you can call it like this:
let mappedObj = objMap(obj, (x) => x * x);
This function uses recursion to square nested objects as well:
function objMap(obj, func) {
return Object.fromEntries(
Object.entries(obj).map(([k, v]) =>
[k, v === Object(v) ? objMap(v, func) : func(v)]
)
);
}
// To square each value you can call it like this:
let mappedObj = objMap(obj, (x) => x * x);
With ES7 / ES2016 you can't use Objects.fromEntries
, but you can achieve the same using Object.assign
in combination with spread operators and computed key names syntax:
let newObj = Object.assign({}, ...Object.entries(obj).map(([k, v]) => ({[k]: v * v})));
ES6 / ES2015 Doesn't allow Object.entries
, but you could use Object.keys
instead:
let newObj = Object.assign({}, ...Object.keys(obj).map(k => ({[k]: obj[k] * obj[k]})));
ES6 also introduced for...of
loops, which allow a more imperative style:
let newObj = {}
for (let [k, v] of Object.entries(obj)) {
newObj[k] = v * v;
}
array.reduce()
Instead of Object.fromEntries
and Object.assign
you can also use reduce for this:
let newObj = Object.entries(obj).reduce((p, [k, v]) => ({ ...p, [k]: v * v }), {});
Inherited properties and the prototype chain:
In some rare situation you may need to map a class-like object which holds properties of an inherited object on its prototype-chain. In such cases Object.keys()
and Object.entries()
won't work, because these functions do not include the prototype chain.
If you need to map inherited properties, you can use for (key in myObj) {...}
.
Here is an example of such situation:
const obj1 = { 'a': 1, 'b': 2, 'c': 3}
const obj2 = Object.create(obj1); // One of multiple ways to inherit an object in JS.
// Here you see how the properties of obj1 sit on the 'prototype' of obj2
console.log(obj2) // Prints: obj2.__proto__ = { 'a': 1, 'b': 2, 'c': 3}
console.log(Object.keys(obj2)); // Prints: an empty Array.
console.log(Object.entries(obj2)); // Prints: an empty Array.
for (let key in obj2) {
console.log(key); // Prints: 'a', 'b', 'c'
}
However, please do me a favor and avoid inheritance. :-)
Object.keys
, which doesn't have any well-defined order. That can be problematic, I suggest usingObject.getOwnPropertyNames
instead.Object.keys
andObject.getOwnPropertyNames
. See developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Object.keys
is implementation-dependent. See stackoverflow.com/a/30919039/1529630