我有一个目标:

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使用这个,所以我不关心跨浏览器问题。)


当前回答

另一种不同的做法是使用自定义的json字符串函数,该函数也可以处理深层对象。如果您打算将其作为json发布到服务器,这可能很有用

常量obj={‘a’:1,‘b’:2,x:{‘c’:3}}const json=json.stringify(obj,(k,v)=>typeof v==“number”?v*v:v)console.log(json)console.log('返回json:',json.parse(json))

其他回答

我需要一个允许修改密钥的版本(基于@Amberlamps和@yonatanmn答案);

var facts = [ // can be an object or array - see jsfiddle below
    {uuid:"asdfasdf",color:"red"},
    {uuid:"sdfgsdfg",color:"green"},
    {uuid:"dfghdfgh",color:"blue"}
];

var factObject = mapObject({}, facts, function(key, item) {
    return [item.uuid, {test:item.color, oldKey:key}];
});

function mapObject(empty, obj, mapFunc){
    return Object.keys(obj).reduce(function(newObj, key) {
        var kvPair = mapFunc(key, obj[key]);
        newObj[kvPair[0]] = kvPair[1];
        return newObj;
    }, empty);
}

factObject(事实对象)=

{
"asdfasdf": {"color":"red","oldKey":"0"},
"sdfgsdfg": {"color":"green","oldKey":"1"},
"dfghdfgh": {"color":"blue","oldKey":"2"}
}

编辑:对传入起始对象{}进行轻微更改。允许为[](如果键是整数)

映射函数在Object.prototype上不存在,但是您可以这样模拟它

var myMap = function ( obj, callback ) {

    var result = {};

    for ( var key in obj ) {
        if ( Object.prototype.hasOwnProperty.call( obj, key ) ) {
            if ( typeof callback === 'function' ) {
                result[ key ] = callback.call( obj, obj[ key ], key, obj );
            }
        }
    }

    return result;

};

var myObject = { 'a': 1, 'b': 2, 'c': 3 };

var newObject = myMap( myObject, function ( value, key ) {
    return value * value;
});

使用以下映射函数定义myObject.map

o => f=> Object.keys(o).reduce((a,c)=> c=='map' ? a : (a[c]=f(o[c],c),a), {})

让map=o=>f=>Object.keys(o).reduce((a,c)=>c=='map'?a:(a[c]=f(o[c],c),a),{})//测试初始化myObject={“a”:1,“b”:2,“c”:3}myObject.map=map(myObject);//你可以这样做,但不建议这样做//(您将看到“map”键任意/所有对象)//Object.prototype.map=map(myObject);//所述OP所需接口newObject=myObject.map(函数(值,标签){返回值*值;});console.log(newObject);

var myObject={“a”:1,“b”:2,“c”:3};Object.keys(myObject).filter((item)=>myObject[item]*=2)console.log(myObject)

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' ]