我有一个目标:

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


当前回答

如果有人在寻找将对象映射到新对象或数组的简单解决方案:

// Maps an object to a new object by applying a function to each key+value pair.
// Takes the object to map and a function from (key, value) to mapped value.
const mapObject = (obj, fn) => {
    const newObj = {};
    Object.keys(obj).forEach(k => { newObj[k] = fn(k, obj[k]); });
    return newObj;
};

// Maps an object to a new array by applying a function to each key+value pair.
// Takes the object to map and a function from (key, value) to mapped value.
const mapObjectToArray = (obj, fn) => (
    Object.keys(obj).map(k => fn(k, obj[k]))
);

这可能不适用于所有对象或所有映射函数,但它适用于简单的浅对象和简单的映射函数,这是我所需要的。

其他回答

这真的很烦人,JS社区的每个人都知道。应该有这样的功能:

const obj1 = {a:4, b:7};
const obj2 = Object.map(obj1, (k,v) => v + 5);

console.log(obj1); // {a:4, b:7}
console.log(obj2); // {a:9, b:12}

这是一个幼稚的实现:

Object.map = function(obj, fn, ctx){

    const ret = {};

    for(let k of Object.keys(obj)){
        ret[k] = fn.call(ctx || null, k, obj[k]);
    });

    return ret;
};

总是要自己实现这一点非常令人讨厌;)

如果您想要一些更复杂的、不干扰Object类的东西,请尝试以下操作:

let map = function (obj, fn, ctx) {
  return Object.keys(obj).reduce((a, b) => {
    a[b] = fn.call(ctx || null, b, obj[b]);
    return a;
  }, {});
};


const x = map({a: 2, b: 4}, (k,v) => {
    return v*2;
});

但将此映射函数添加到Object是安全的,只是不要添加到Object.prototype。

Object.map = ... // fairly safe
Object.prototype.map ... // not ok

我来到这里是为了查找并回答将对象映射到数组的问题,结果得到了这个页面。如果你来这里寻找与我相同的答案,这里是如何映射和对象到一个数组。

您可以使用map从对象返回一个新数组,如下所示:

var newObject = Object.keys(myObject).map(function(key) {
   return myObject[key];
});

我需要一个函数,不仅可以选择性地映射(也可以选择性地)值,还可以映射键。原始对象不应更改。该对象也仅包含基本值。

function mappedObject(obj, keyMapper, valueMapper) {

    const mapped = {};
    const keys   = Object.keys(obj);
    const mapKey = typeof keyMapper == 'function';
    const mapVal = typeof valueMapper == 'function';

    for (let i = 0; i < keys.length; i++) {
        const key = mapKey ? keyMapper(keys[i]) : keys[i];
        const val = mapVal ? valueMapper(obj[keys[i]]) : obj[keys[i]];
        mapped[key] = val;
    }

    return mapped;
}

使用传递keymapper和valuemapper函数:

const o1 = { x: 1, c: 2 }
mappedObject(o1, k => k + '0', v => v + 1) // {x0: 2, c0: 3}

这是另一个版本,它允许映射函数根据当前键和值声明任意数量的新财产(键和值)。E: 现在也可以使用数组。

Object.defineProperty(Object.prototype,“mapEntries”{value:函数(f,a=Array.isArray(this)?[]:{}) {return Object.entries(this).reduce((o,[k,v])=>对象赋值(o,f(v,Array.isArray(a)?数字(k):k,this)),a) ;}});常量数据={a:1,b:2,c:3};常量计算=(v,k)=>({[k+'_square']:v*v,[k+'_cube']:v*v*v});console.log(data.mapEntries(计算));// {//“a_square”:1,“a_scube”:1,//“b_square”:4,“b_cube”:8,//“c_square”:9,“c_cube”:27// }//阵列演示:常量arr=[“a”、“b”、“c”];常量重复=(v,i)=>({[i*2]:v,[i*2+1]:v+v});console.log(arr.mapEntries(重复));//[“a”、“aa”、“b”、“bb”、“c”、“cc”]

settings = {
  message_notification: {
    value: true,
    is_active: true,
    slug: 'message_notification',
    title: 'Message Notification'
  },
  support_notification: {
    value: true,
    is_active: true,
    slug: 'support_notification',
    title: 'Support Notification'
  },
};

let keys = Object.keys(settings);
keys.map(key=> settings[key].value = false )
console.log(settings)