Is there a native method in JavaScript for mapping over objects, similar to Array.prototype.map? For example, given an object like this:
myObject = { ‘a’: 1, ‘b’: 2, ‘c’: 3 }
I want to use a method like this:
newObject = myObject.map(function (value, label) {
return value * value;
});
// newObject should be { ‘a’: 1, ‘b’: 4, ‘c’: 9 }
Does JavaScript have a map function for objects? I’m specifically looking for a solution that works in Node.js, so cross-browser compatibility is not a concern.
You can also use Object.entries() to map over key-value pairs directly:
function mapObject(obj, callback) {
return Object.fromEntries(
Object.entries(obj).map(([key, value]) => [key, callback(value, key)])
);
}
const myObject = { 'a': 1, 'b': 2, 'c': 3 };
const newObject = mapObject(myObject, function(value, label) {
return value * value;
});
console.log(newObject); // { 'a': 1, 'b': 4, 'c': 9 }
JavaScript does not have a built-in map method for objects like it does for arrays.
However, you can achieve similar functionality by creating your own utility function or using , Object.values()
, or Object.entries().
Using Object.keys()
You can create a custom map function that iterates over the keys of the object:
function mapObject(obj, callback) {
const newObject = {};
Object.keys(obj).forEach((key) => {
newObject[key] = callback(obj[key], key);
});
return newObject;
}
const myObject = { 'a': 1, 'b': 2, 'c': 3 };
const newObject = mapObject(myObject, function(value, label) {
return value * value;
});
console.log(newObject); // { 'a': 1, 'b': 4, 'c': 9 }
If you want to ignore the keys and just transform the values, you can use Object.values()
and then rebuild the object:
function mapObject(obj, callback) {
const values = Object.values(obj);
const newValues = values.map((value) => callback(value));
return Object.assign({}, ...Object.keys(obj).map((key, index) => ({ [key]: newValues[index] })));
}
const myObject = { 'a': 1, 'b': 2, 'c': 3 };
const newObject = mapObject(myObject, function(value) {
return value * value;
});
console.log(newObject); // { 'a': 1, 'b': 4, 'c': 9 }