I have an object:
myObject = { \'a\': 1, \'b\': 2, \'c\': 3 }
I am looking for a native method, similar to Array.prototype.map
You could use Object.keys and then forEach
over the returned array of keys:
var myObject = { 'a': 1, 'b': 2, 'c': 3 },
newObject = {};
Object.keys(myObject).forEach(function (key) {
var value = myObject[key];
newObject[key] = value * value;
});
Or in a more modular fashion:
function map(obj, callback) {
var result = {};
Object.keys(obj).forEach(function (key) {
result[key] = callback.call(obj, obj[key], key, obj);
});
return result;
}
newObject = map(myObject, function(x) { return x * x; });
Note that Object.keys
returns an array containing only the object's own enumerable properties, thus it behaves like a for..in
loop with a hasOwnProperty
check.