[javascript] map function for objects (instead of arrays)

I have an object:

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

I am looking for a native method, 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 }

Does JavaScript have such a map function for objects? (I want this for Node.JS, so I don't care about cross-browser issues.)

The answer is


Use following map function to define myObject.map

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

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



// TEST init

myObject = { 'a': 1, 'b': 2, 'c': 3 }
myObject.map = map(myObject);        

// you can do this instead above line but it is not recommended 
// ( you will see `map` key any/all objects)
// Object.prototype.map = map(myObject);

// OP desired interface described in question
newObject = myObject.map(function (value, label) {
    return  value * value;
});

console.log(newObject);
_x000D_
_x000D_
_x000D_


JavaScript just got the new Object.fromEntries method.

Example

_x000D_
_x000D_
function mapObject (obj, fn) {_x000D_
  return Object.fromEntries(_x000D_
    Object_x000D_
      .entries(obj)_x000D_
      .map(fn)_x000D_
  )_x000D_
}_x000D_
_x000D_
const myObject = { a: 1, b: 2, c: 3 }_x000D_
const myNewObject = mapObject(myObject, ([key, value]) => ([key, value * value]))_x000D_
console.log(myNewObject)
_x000D_
_x000D_
_x000D_

Explanation

The code above converts the Object into an nested Array ([[<key>,<value>], ...]) wich you can map over. Object.fromEntries converts the Array back to an Object.

The cool thing about this pattern, is that you can now easily take object keys into account while mapping.

Documentation

Browser Support

Object.fromEntries is currently only supported by these browsers/engines, nevertheless there are polyfills available (e.g @babel/polyfill).


It's pretty easy to write one:

Object.map = function(o, f, ctx) {
    ctx = ctx || this;
    var result = {};
    Object.keys(o).forEach(function(k) {
        result[k] = f.call(ctx, o[k], k, o); 
    });
    return result;
}

with example code:

> o = { a: 1, b: 2, c: 3 };
> r = Object.map(o, function(v, k, o) {
     return v * v;
  });
> r
{ a : 1, b: 4, c: 9 }

NB: this version also allows you to (optionally) set the this context for the callback, just like the Array method.

EDIT - changed to remove use of Object.prototype, to ensure that it doesn't clash with any existing property named map on the object.


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.

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

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.


My response is largely based off the highest rated response here and hopefully everyone understands (have the same explanation on my GitHub, too). This is why his impementation with map works:

Object.keys(images).map((key) => images[key] = 'url(' + '"' + images[key] + '"' +    
')');

The purpose of the function is to take an object and modify the original contents of the object using a method available to all objects (objects and arrays alike) without returning an array. Almost everything within JS is an object, and for that reason elements further down the pipeline of inheritance can potentially technically use those available to those up the line (and the reverse it appears).

The reason that this works is due to the .map functions returning an array REQUIRING that you provide an explicit or implicit RETURN of an array instead of simply modifying an existing object. You essentially trick the program into thinking the object is an array by using Object.keys which will allow you to use the map function with its acting on the values the individual keys are associated with (I actually accidentally returned arrays but fixed it). As long as there isn't a return in the normal sense, there will be no array created with the original object stil intact and modified as programmed.

This particular program takes an object called images and takes the values of its keys and appends url tags for use within another function. Original is this:

var images = { 
snow: 'https://www.trbimg.com/img-5aa059f5/turbine/bs-md-weather-20180305', 
sunny: 'http://www.cubaweather.org/images/weather-photos/large/Sunny-morning-east-   
Matanzas-city- Cuba-20170131-1080.jpg', 
rain: 'https://i.pinimg.com/originals/23/d8
/ab/23d8ab1eebc72a123cebc80ce32b43d8.jpg' };

...and modified is this:

var images = { 
snow: url('https://www.trbimg.com/img-5aa059f5/turbine/bs-md-weather-20180305'),     
sunny: url('http://www.cubaweather.org/images/weather-photos/large/Sunny-morning-   
east-Matanzas-city- Cuba-20170131-1080.jpg'), 
rain: url('https://i.pinimg.com/originals/23/d8
/ab/23d8ab1eebc72a123cebc80ce32b43d8.jpg') 
};

The object's original structure is left intact allowing for normal property access as long as there isn't a return. Do NOT have it return an array like normal and everything will be fine. The goal is REASSIGNING the original values (images[key]) to what is wanted and not anything else. As far as I know, in order to prevent array output there HAS to be REASSIGNMENT of images[key] and no implicit or explicit request to return an array (variable assignment does this and was glitching back and forth for me).

EDIT:

Going to address his other method regarding new object creation to avoid modifying original object (and reassignment appears to still be necessary in order to avoid accidentally creating an array as output). These functions use arrow syntax and are if you simply want to create a new object for future use.

const mapper = (obj, mapFn) => Object.keys(obj).reduce((result, key) => {
                result[key] = mapFn(obj)[key];
                return result;
            }, {});

var newImages = mapper(images, (value) => value);

The way these functions work is like so:

mapFn takes the function to be added later (in this case (value) => value) and simply returns whatever is stored there as a value for that key (or multiplied by two if you change the return value like he did) in mapFn(obj)[key],

and then redefines the original value associated with the key in result[key] = mapFn(obj)[key]

and returns the operation performed on result (the accumulator located in the brackets initiated at the end of the .reduce function).

All of this is being performed on the chosen object and STILL there CANNOT be an implicit request for a returned array and only works when reassigning values as far as I can tell. This requires some mental gymnastics but reduces the lines of code needed as can be seen above. Output is exactly the same as can be seen below:

{snow: "https://www.trbimg.com/img-5aa059f5/turbine/bs-   
md-weather-20180305", sunny: "http://www.cubaweather.org/images/weather-
photos/l…morning-east-Matanzas-city-Cuba-20170131-1080.jpg", rain: 
"https://i.pinimg.com/originals/23/d8
/ab/23d8ab1eebc72a123cebc80ce32b43d8.jpg"}

Keep in mind this worked with NON-NUMBERS. You CAN duplicate ANY object by SIMPLY RETURNING THE VALUE in the mapFN function.


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


Object.prototype.map = function(fn){
    var oReturn = {};
    for (sCurObjectPropertyName in this) {
        oReturn[sCurObjectPropertyName] = fn(this[sCurObjectPropertyName], sCurObjectPropertyName);
    }
    return oReturn;
}
Object.defineProperty(Object.prototype,'map',{enumerable:false});





newObject = myObject.map(function (value, label) {
    return value * value;
});


// newObject is now { 'a': 1, 'b': 4, 'c': 9 }

I specifically wanted to use the same function that I was using for arrays for a single object, and wanted to keep it simple. This worked for me:

var mapped = [item].map(myMapFunction).pop();

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


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

for (var key in myObject) {
  if (myObject.hasOwnProperty(key)) {
    myObject[key] *= 2;
  }
}

console.log(myObject);
// { 'a': 2, 'b': 4, 'c': 6 }
_x000D_
_x000D_
_x000D_


No native methods, but lodash#mapValues will do the job brilliantly

_.mapValues({ 'a': 1, 'b': 2, 'c': 3} , function(num) { return num * 3; });
// ? { 'a': 3, 'b': 6, 'c': 9 }

Minimal version (es6):

Object.entries(obj).reduce((a, [k, v]) => (a[k] = v * v, a), {})

You can convert an object to array simply by using the following:

You can convert the object values to an array:

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

let valuesArray = Object.values(myObject);

console.log(valuesArray);
_x000D_
_x000D_
_x000D_

You can convert the object keys to an array:

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

let keysArray = Object.keys(myObject);

console.log(keysArray);
_x000D_
_x000D_
_x000D_

Now you can perform normal array operations, including the 'map' function


Hey wrote a little mapper function that might help.

    function propertyMapper(object, src){
         for (var property in object) {   
           for (var sourceProp in src) {
               if(property === sourceProp){
                 if(Object.prototype.toString.call( property ) === '[object Array]'){
                   propertyMapper(object[property], src[sourceProp]);
                   }else{
                   object[property] = src[sourceProp];
                }
              }
            }
         }
      }

If you're interested in mapping not only values but also keys, I have written Object.map(valueMapper, keyMapper), that behaves this way:

var source = { a: 1, b: 2 };
function sum(x) { return x + x }

source.map(sum);            // returns { a: 2, b: 4 }
source.map(undefined, sum); // returns { aa: 1, bb: 2 }
source.map(sum, sum);       // returns { aa: 2, bb: 4 }

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:

_x000D_
_x000D_
myObject = { 'a': 1, 'b': 2, 'c': 3 };_x000D_
_x000D_
myObject.map = function mapForObject(callback)_x000D_
{_x000D_
  var result = {};_x000D_
  for(var property in this){_x000D_
    if(this.hasOwnProperty(property) && property != "map"){_x000D_
      result[property] = callback(this[property],property,this);_x000D_
    }_x000D_
  }_x000D_
  return result;_x000D_
}_x000D_
_x000D_
newObject = myObject.map(function (value, label) {_x000D_
  return value * value;_x000D_
});_x000D_
console.log("newObject is now",newObject);
_x000D_
_x000D_
_x000D_ alternative test code here

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).


You could use Object.keys and then forEach over the returned array of keys:

var myObject = { 'a': 1, 'b': 2, 'c': 3 },
    newObject = {};
Object.keys(myObject).forEach(function (key) {
    var value = myObject[key];
    newObject[key] = value * value;
});

Or in a more modular fashion:

function map(obj, callback) {
    var result = {};
    Object.keys(obj).forEach(function (key) {
        result[key] = callback.call(obj, obj[key], key, obj);
    });
    return result;
}

newObject = map(myObject, function(x) { return x * x; });

Note that Object.keys returns an array containing only the object's own enumerable properties, thus it behaves like a for..in loop with a hasOwnProperty check.


First, convert your HTMLCollection using Object.entries(collection). Then it’s an iterable you can now use the .map method on it.

Object.entries(collection).map(...)

reference https://medium.com/@js_tut/calling-javascript-code-on-multiple-div-elements-without-the-id-attribute-97ff6a50f31


I came upon this as a first-item in a Google search trying to learn to do this, and thought I would share for other folsk finding this recently the solution I found, which uses the npm package immutable.

I think its interesting to share because immutable uses the OP's EXACT situation in their own documentation - the following is not my own code but pulled from the current immutable-js documentation:

const { Seq } = require('immutable')
const myObject = { a: 1, b: 2, c: 3 }
Seq(myObject).map(x => x * x).toObject();
// { a: 1, b: 4, c: 9 } 

Not that Seq has other properties ("Seq describes a lazy operation, allowing them to efficiently chain use of all the higher-order collection methods (such as map and filter) by not creating intermediate collections") and that some other immutable-js data structures might also do the job quite efficiently.

Anyone using this method will of course have to npm install immutable and might want to read the docs:

https://facebook.github.io/immutable-js/


_x000D_
_x000D_
const orig = { 'a': 1, 'b': 2, 'c': 3 }_x000D_
_x000D_
const result = _.transform(orig, (r, v, k) => r[k.trim()] = v * 2);_x000D_
_x000D_
console.log(result);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Use new _.transform() to transforms object.


The accepted answer has two drawbacks:

  • It misuses Array.prototype.reduce, because reducing means to change the structure of a composite type, which doesn't happen in this case.
  • It is not particularly reusable

An ES6/ES2015 functional approach

Please note that all functions are defined in curried form.

_x000D_
_x000D_
// small, reusable auxiliary functions_x000D_
_x000D_
const keys = o => Object.keys(o);_x000D_
_x000D_
const assign = (...o) => Object.assign({}, ...o);_x000D_
_x000D_
const map = f => xs => xs.map(x => f(x));_x000D_
_x000D_
const mul = y => x => x * y;_x000D_
_x000D_
const sqr = x => mul(x) (x);_x000D_
_x000D_
_x000D_
// the actual map function_x000D_
_x000D_
const omap = f => o => {_x000D_
  o = assign(o); // A_x000D_
  map(x => o[x] = f(o[x])) (keys(o)); // B_x000D_
  return o;_x000D_
};_x000D_
_x000D_
_x000D_
// mock data_x000D_
_x000D_
const o = {"a":1, "b":2, "c":3};_x000D_
_x000D_
_x000D_
// and run_x000D_
_x000D_
console.log(omap(sqr) (o));_x000D_
console.log(omap(mul(10)) (o));
_x000D_
_x000D_
_x000D_

  • In line A o is reassigned. Since Javascript passes reference values by sharing, a shallow copy of o is generated. We are now able to mutate o within omap without mutating o in the parent scope.
  • In line B map's return value is ignored, because map performs a mutation of o. Since this side effect remains within omap and isn't visible in the parent scope, it is totally acceptable.

This is not the fastest solution, but a declarative and reusable one. Here is the same implementation as a one-line, succinct but less readable:

const omap = f => o => (o = assign(o), map(x => o[x] = f(o[x])) (keys(o)), o);

Addendum - why are objects not iterable by default?

ES2015 specified the iterator and iterable protocols. But objects are still not iterable and thus not mappable. The reason is the mixing of data and program level.


The map function does not exist on the Object.prototype however you can emulate it like so

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;
});

This is really annoying, and everyone in the JS community knows it. There should be this functionality:

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}

here is the naïve implementation:

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;
};

it is super annoying to have to implement this yourself all the time ;)

If you want something a little more sophisticated, that doesn't interfere with the Object class, try this:

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;
});

but it is safe to add this map function to Object, just don't add to Object.prototype.

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

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)

you can use map method and forEach on arrays but if you want to use it on Object then you can use it with twist like below:

Using Javascript (ES6)

var obj = { 'a': 2, 'b': 4, 'c': 6 };   
Object.entries(obj).map( v => obj[v[0]] *= v[1] );
console.log(obj); //it will log as {a: 4, b: 16, c: 36}

var obj2 = { 'a': 4, 'b': 8, 'c': 10 };
Object.entries(obj2).forEach( v => obj2[v[0]] *= v[1] );
console.log(obj2); //it will log as {a: 16, b: 64, c: 100}

Using jQuery

var ob = { 'a': 2, 'b': 4, 'c': 6 };
$.map(ob, function (val, key) {
   ob[key] *= val;
});
console.log(ob) //it will log as {a: 4, b: 16, c: 36}

Or you can use other loops also like $.each method as below example:

$.each(ob,function (key, value) {
  ob[key] *= value;
});
console.log(ob) //it will also log as {a: 4, b: 16, c: 36}

I handle only strings to reduce exemptions:

Object.keys(params).map(k => typeof params[k] == "string" ? params[k] = params[k].trim() : null);

Based on @Amberlamps answer, here's a utility function (as a comment it looked ugly)

function mapObject(obj, mapFunc){
    return Object.keys(obj).reduce(function(newObj, value) {
        newObj[value] = mapFunc(obj[value]);
        return newObj;
    }, {});
}

and the use is:

var obj = {a:1, b:3, c:5}
function double(x){return x * 2}

var newObj = mapObject(obj, double);
//=>  {a: 2, b: 6, c: 10}

Object Mapper in TypeScript

I like the examples that use Object.fromEntries such as this one, but still, they are not very easy to use. The answers that use Object.keys and then look up the key are actually doing multiple look-ups that may not be necessary.

I wished there was an Object.map function, but we can create our own and call it objectMap with the ability to modify both key and value:

Usage (JavaScript):

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

// keep the key and modify the value
let obj = objectMap(myObject, val => val * 2);
// obj = { a: 2, b: 4, c: 6 }


// modify both key and value
obj = objectMap(myObject,
    val => val * 2 + '',
    key => (key + key).toUpperCase());
// obj = { AA: '2', BB: '4', CC: '6' }

Code (TypeScript):

interface Dictionary<T> {
    [key: string]: T;
}

function objectMap<TValue, TResult>(
    obj: Dictionary<TValue>,
    valSelector: (val: TValue, obj: Dictionary<TValue>) => TResult,
    keySelector?: (key: string, obj: Dictionary<TValue>) => string,
    ctx?: Dictionary<TValue>
) {
    const ret = {} as Dictionary<TResult>;
    for (const key of Object.keys(obj)) {
        const retKey = keySelector
            ? keySelector.call(ctx || null, key, obj)
            : key;
        const retVal = valSelector.call(ctx || null, obj[key], obj);
        ret[retKey] = retVal;
    }
    return ret;
}

If you are not using TypeScript then copy the above code in TypeScript Playground to get the JavaScript code.

Also, the reason I put keySelector after valSelector in the parameter list, is because it is optional.

* Some credit go to alexander-mills' answer.


How about a one-liner in JS ES10 / ES2019 ?

Making use of Object.entries() and Object.fromEntries():

let newObj = Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, v * v]));

The same thing written as a function:

function objMap(obj, func) {
  return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, func(v)]));
}

// To square each value you can call it like this:
let mappedObj = objMap(obj, (x) => x * x);

This function uses recursion to square nested objects as well:

function objMap(obj, func) {
  return Object.fromEntries(
    Object.entries(obj).map(([k, v]) => 
      [k, v === Object(v) ? objMap(v, func) : func(v)]
    )
  );
}

// To square each value you can call it like this:
let mappedObj = objMap(obj, (x) => x * x);

With ES7 / ES2016 you cant' use Objects.fromEntries, but you can achieve the same using Object.assign in combination with spread operators and computed key names syntax:

let newObj = Object.assign(...Object.entries(obj).map(([k, v]) => ({[k]: v * v})));

ES6 / ES2015 Doesn't allow Object.entires, but you could use Object.keys instead:

let newObj = Object.assign(...Object.keys(obj).map(k => ({[k]: obj[k] * obj[k]})));

ES6 also introduced for...of loops, which allow a more imperative style:

let newObj = {}

for (let [k, v] of Object.entries(obj)) {
  newObj[k] = v * v;
}


array.reduce()

Instead of Object.fromEntries and Object.assign you can also use reduce for this:

let newObj = Object.entries(obj).reduce((p, [k, v]) => ({ ...p, [k]: v * v }), {});


Inherited properties and the prototype chain:

In some rare situation you may need to map a class-like object which holds properties of an inherited object on its prototype-chain. In such cases Object.keys() and Object.entries() won't work, because these functions do not include the prototype chain.

If you need to map inherited properties, you can use for (key in myObj) {...}.

Here is an example of such situation:

const obj1 = { 'a': 1, 'b': 2, 'c': 3}
const obj2 = Object.create(obj1);  // One of multiple ways to inherit an object in JS.

// Here you see how the properties of obj1 sit on the 'prototype' of obj2
console.log(obj2)  // Prints: obj2.__proto__ = { 'a': 1, 'b': 2, 'c': 3}

console.log(Object.keys(obj2));  // Prints: an empty Array.
console.log(Object.entries(obj2));  // Prints: an empty Array.

for (let key in obj2) {
  console.log(key);              // Prints: 'a', 'b', 'c'
}

However, please do me a favor and avoid inheritance. :-)


I came here looking to find and answer for mapping an object to an array and got this page as a result. In case you came here looking for the same answer I was, here is how you can map and object to an array.

You can use map to return a new array from the object like so:

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

ES6:

Object.prototype.map = function(mapFunc) {
    return Object.keys(this).map((key, index) => mapFunc(key, this[key], index));
}

ES2015:

Object.prototype.map = function (mapFunc) {
    var _this = this;

    return Object.keys(this).map(function (key, index) {
        return mapFunc(key, _this[key], index);
    });
};

test in node:

> a = {foo: "bar"}
{ foo: 'bar' }
> a.map((k,v,i) => v)
[ 'bar' ]

2020 updates, overwriting Object.prototype

Object.prototype.map = function(func){
    for(const [k, v] of Object.entries(this)){
        func(k, v);
    }
    return this;
}

Object.prototype.reject = function(func){
    for(const [k, v] of Object.entries(this)){
        if(func(k, v)){
            delete this[k];
        }
    }
    return this;
}

Object.prototype.filter = function(func){
    let res = {};
    for(const [k, v] of Object.entries(this)){
        if(!func(k, v)){
            delete this[k];
        }
    }
    return this;
}

a = {
    1: ['a', '1'],
    2: ['b', '2'],
    3: ['a', '3'],
};

console.log(Object.assign({}, a).map((k, v) => v.push('nice')));
// {
//   '1': [ 'a', '1', 'nice' ],
//   '2': [ 'b', '2', 'nice' ],
//   '3': [ 'a', '3', 'nice' ]
// }

console.log(Object.assign({}, a).reject((k, v)=>v[0] === 'a'));
// { '2': [ 'b', '2', 'nice' ] }

console.log(Object.assign({}, a).filter((k, v)=>v[0] === 'a'));
// { '1': [ 'a', '1', 'nice' ], '3': [ 'a', '3', 'nice' ] }

If anyone was looking for a simple solution that maps an object to a new object or to an array:

// 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]))
);

This may not work for all objects or all mapping functions, but it works for plain shallow objects and straightforward mapping functions which is all I needed.


I needed a version that allowed modifying the keys as well (based on @Amberlamps and @yonatanmn answers);

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"}
}

Edit: slight change to pass in the starting object {}. Allows it to be [] (if the keys are integers)


const mapObject = (targetObject, callbackFn) => {
    if (!targetObject) return targetObject;
    if (Array.isArray(targetObject)){
        return targetObject.map((v)=>mapObject(v, callbackFn))
    }
    return Object.entries(targetObject).reduce((acc,[key, value]) => {
        const res = callbackFn(key, value);
        if (!Array.isArray(res) && typeof res ==='object'){
            return {...acc, [key]: mapObject(res, callbackFn)}
        }
        if (Array.isArray(res)){
            return {...acc, [key]: res.map((v)=>mapObject(v, callbackFn))}
        }
        return {...acc, [key]: res};
    },{})
};
const mapped = mapObject(a,(key,value)=> {
    if (!Array.isArray(value) && key === 'a') return ;
    if (!Array.isArray(value) && key === 'e') return [];
    if (!Array.isArray(value) && key === 'g') return value * value;
    return value;
});
console.log(JSON.stringify(mapped)); 
// {"b":2,"c":[{"d":2,"e":[],"f":[{"g":4}]}]}

This function goes recursively through the object and arrays of objects. Attributes can be deleted if returned undefined


Define a function mapEntries.

mapEntries takes a callback function that is called on each entry in the object with the parameters value, key and object. It should return the a new value.

mapEntries should return a new object with the new values returned from the callback.

Object.defineProperty(Object.prototype, 'mapEntries', {
  enumerable: false,
  value: function (mapEntriesCallback) {
    return Object.fromEntries(
      Object.entries(this).map(
        ([key, value]) => [key, mapEntriesCallback(value, key, this)]
      )
    )
  }
})


// Usage example:

var object = {a: 1, b: 2, c: 3}
var newObject = object.mapEntries(value => value * value)
console.log(newObject)
//> {a: 1, b: 4, c: 9}

Edit: A previous version didn't specify that this is not an enumerable property


EDIT: The canonical way using newer JavaScript features is -

const identity = x =>
  x

const omap = (f = identity, o = {}) =>
  Object.fromEntries(
    Object.entries(o).map(([ k, v ]) =>
      [ k, f(v) ]
    )
  )

Where o is some object and f is your mapping function. Or we could say, given a function from a -> b, and an object with values of type a, produce an object with values of type b. As a pseudo type signature -

// omap : (a -> b, { a }) -> { b }

The original answer was written to demonstrate a powerful combinator, mapReduce which allows us to think of our transformation in a different way

  1. m, the mapping function – gives you a chance to transform the incoming element before…
  2. r, the reducing function – this function combines the accumulator with the result of the mapped element

Intuitively, mapReduce creates a new reducer we can plug directly into Array.prototype.reduce. But more importantly, we can implement our object functor implementation omap plainly by utilizing the object monoid, Object.assign and {}.

_x000D_
_x000D_
const identity = x =>_x000D_
  x_x000D_
  _x000D_
const mapReduce = (m, r) =>_x000D_
  (a, x) => r (a, m (x))_x000D_
_x000D_
const omap = (f = identity, o = {}) =>_x000D_
  Object_x000D_
    .keys (o)_x000D_
    .reduce_x000D_
      ( mapReduce_x000D_
          ( k => ({ [k]: f (o[k]) })_x000D_
          , Object.assign_x000D_
          )_x000D_
      , {}_x000D_
      )_x000D_
          _x000D_
const square = x =>_x000D_
  x * x_x000D_
  _x000D_
const data =_x000D_
  { a : 1, b : 2, c : 3 }_x000D_
  _x000D_
console .log (omap (square, data))_x000D_
// { a : 1, b : 4, c : 9 }
_x000D_
_x000D_
_x000D_

Notice the only part of the program we actually had to write is the mapping implementation itself –

k => ({ [k]: f (o[k]) })

Which says, given a known object o and some key k, construct an object and whose computed property k is the result of calling f on the key's value, o[k].

We get a glimpse of mapReduce's sequencing potential if we first abstract oreduce

// oreduce : (string * a -> string * b, b, { a }) -> { b }
const oreduce = (f = identity, r = null, o = {}) =>
  Object
    .keys (o)
    .reduce
      ( mapReduce
          ( k => [ k, o[k] ]
          , f
          )
      , r
      )

// omap : (a -> b, {a}) -> {b}
const omap = (f = identity, o = {}) =>
  oreduce
    ( mapReduce
        ( ([ k, v ]) =>
            ({ [k]: f (v) })
        , Object.assign
        )
    , {}
    , o
    )

Everything works the same, but omap can be defined at a higher-level now. Of course the new Object.entries makes this look silly, but the exercise is still important to the learner.

You won't see the full potential of mapReduce here, but I share this answer because it's interesting to see just how many places it can be applied. If you're interested in how it is derived and other ways it could be useful, please see this answer.


A different take on it is to use a custom json stringify function that can also work on deep objects. This might be useful if you intend to post it to the server anyway as json

_x000D_
_x000D_
const obj = { 'a': 1, 'b': 2, x: {'c': 3 }}_x000D_
const json = JSON.stringify(obj, (k, v) => typeof v === 'number' ? v * v : v)_x000D_
_x000D_
console.log(json)_x000D_
console.log('back to json:', JSON.parse(json))
_x000D_
_x000D_
_x000D_


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to functional-programming

Dart: mapping a list (list.map) Index inside map() function functional way to iterate over range (ES6/7) How can I count occurrences with groupBy? How do I use the includes method in lodash to check if an object is in the collection? Does Java SE 8 have Pairs or Tuples? Functional style of Java 8's Optional.ifPresent and if-not-Present? What is difference between functional and imperative programming languages? How does functools partial do what it does? map function for objects (instead of arrays)

Examples related to map-function

Passing multiple parameters to pool.map() function in Python Are list-comprehensions and functional functions faster than "for loops"? map function for objects (instead of arrays) Mapping over values in a python dictionary Understanding the map function Java: is there a map function? Getting a map() to return a list in Python 3.x List comprehension vs map