I have an object:
myObject = { \'a\': 1, \'b\': 2, \'c\': 3 }
I am looking for a native method, similar to Array.prototype.map
To responds more closely to what precisely the OP asked for, the OP wants an object:
myObject = { 'a': 1, 'b': 2, 'c': 3 }
to have a map method myObject.map,
similar to Array.prototype.map that would be used as follows:
newObject = myObject.map(function (value, label) { return value * value; }); // newObject is now { 'a': 1, 'b': 4, 'c': 9 }
The imho best (measured in terms to "close to what is asked" + "no ES{5,6,7} required needlessly") answer would be:
myObject.map = function mapForObject(callback)
{
var result = {};
for(var property in this){
if(this.hasOwnProperty(property) && property != "map"){
result[property] = callback(this[property],property,this);
}
}
return result;
}
The code above avoids intentionally using any language features, only available in recent ECMAScript editions. With the code above the problem can be solved lke this:
myObject = { 'a': 1, 'b': 2, 'c': 3 };
myObject.map = function mapForObject(callback)
{
var result = {};
for(var property in this){
if(this.hasOwnProperty(property) && property != "map"){
result[property] = callback(this[property],property,this);
}
}
return result;
}
newObject = myObject.map(function (value, label) {
return value * value;
});
console.log("newObject is now",newObject);
Besides frowned upon by some, it would be a possibility to insert the solution in the prototype chain like this.
Object.prototype.map = function(callback)
{
var result = {};
for(var property in this){
if(this.hasOwnProperty(property)){
result[property] = callback(this[property],property,this);
}
}
return result;
}
Something, which when done with careful oversight should not have any ill effects and not impact map method of other objects (i.e. Array's map).