map function for objects (instead of arrays)

前端 未结 30 2643
无人及你
无人及你 2020-11-22 04:23

I have an object:

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

I am looking for a native method, similar to Array.prototype.map

30条回答
  •  感动是毒
    2020-11-22 05:06

    For maximum performance.

    If your object doesn't change often but needs to be iterated on often I suggest using a native Map as a cache.

    // example object
    var obj = {a: 1, b: 2, c: 'something'};
    
    // caching map
    var objMap = new Map(Object.entries(obj));
    
    // fast iteration on Map object
    objMap.forEach((item, key) => {
      // do something with an item
      console.log(key, item);
    });

    Object.entries already works in Chrome, Edge, Firefox and beta Opera so it's a future-proof feature. It's from ES7 so polyfill it https://github.com/es-shims/Object.entries for IE where it doesn't work.

提交回复
热议问题