我有一个目标:
myObject = { 'a': 1, 'b': 2, 'c': 3 }
我正在寻找一个本地方法,类似于Array.prototype.map,可按如下方式使用:
newObject = myObject.map(function (value, label) {
return value * value;
});
// newObject is now { 'a': 1, 'b': 4, 'c': 9 }
JavaScript是否有这样的对象映射函数?(我希望Node.JS使用这个,所以我不关心跨浏览器问题。)
ES6:
Object.prototype.map = function(mapFunc) {
return Object.keys(this).map((key, index) => mapFunc(key, this[key], index));
}
2015年:
Object.prototype.map = function (mapFunc) {
var _this = this;
return Object.keys(this).map(function (key, index) {
return mapFunc(key, _this[key], index);
});
};
节点中的测试:
> a = {foo: "bar"}
{ foo: 'bar' }
> a.map((k,v,i) => v)
[ 'bar' ]