map function for objects (instead of arrays)

Asked 2023-09-21 08:11:51 View 596,061

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

  • Most answers use Object.keys, which doesn't have any well-defined order. That can be problematic, I suggest using Object.getOwnPropertyNames instead. - anyone
  • @Oriol are you sure about that? According to the MDN web docs, the ordering of array elements is consistent between Object.keys and Object.getOwnPropertyNames. See developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - anyone
  • @Bart The order of Object.keys is implementation-dependent. See stackoverflow.com/a/30919039/1529630 - anyone
  • @Oriol You're not supposed to rely on the order of keys in objects anyway, so its kinda irrelevant to the question - since he never specified that the order mattered to him. And if order mattered to him, he shouldn't be using an object at all anyway. - anyone
  • someone please put some of these solutions in an npm package, with tests please - anyone

Answers

There is no native map to the Object object, but how about this:

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

Object.keys(myObject).forEach(function(key, index) {
  myObject[key] *= 2;
});

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

But you could easily iterate over an object using for ... in:

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 }

Update

A lot of people are mentioning that the previous methods do not return a new object, but rather operate on the object itself. For that matter I wanted to add another solution that returns a new object and leaves the original object as it is:

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

// returns a new object with the values at each key mapped using mapFn(value)
function objectMap(object, mapFn) {
  return Object.keys(object).reduce(function(result, key) {
    result[key] = mapFn(object[key])
    return result
  }, {})
}

var newObject = objectMap(myObject, function(value) {
  return value * 2
})

console.log(newObject);
// => { 'a': 2, 'b': 4, 'c': 6 }

console.log(myObject);
// => { 'a': 1, 'b': 2, 'c': 3 }

Array.prototype.reduce reduces an array to a single value by somewhat merging the previous value with the current. The chain is initialized by an empty object {}. On every iteration a new key of myObject is added with twice the key as the value.

Update

With new ES6 features, there is a more elegant way to express objectMap.

const objectMap = (obj, fn) =>
  Object.fromEntries(
    Object.entries(obj).map(
      ([k, v], i) => [k, fn(v, k, i)]
    )
  )
  
const myObject = { a: 1, b: 2, c: 3 }

console.log(objectMap(myObject, v => 2 * v)) 

Answered   2023-09-21 08:11:51

  • @KhalilRavanna I think you've misread the code here - this answer isn't using map correctly because it isn't doing a return - it's abusing map as if it were a forEach call. If he actually did return myObject[value] * 2 then the result would be an array containing the original values doubled, instead of an object containing the original keys with doubled values, the latter clearly being what the OP asked for. - anyone
  • @Amberlamps your .reduce example is OK, but IMHO it still falls a long way short of the convenience of a .map for Objects, since your .reduce callback not only has to match the way that .reduce works, but also requires that myObject be available in the lexical scope. The latter in particular makes it impossible to just pass a function reference in the callback, requiring an in-place anonymous function instead. - anyone
  • TBH I would have rather upvoted an answer that only (or originally) provided the second solution presented in this answer. The first one works and is not necessarily wrong, but as others have stated, I don't like to see map being used that way. When I see map, my mind is automatically thinking "immutable data structure" - anyone
  • .map is not the appropriate method to use when you aren't going to use the resulting mapped array - if you want side-effects only, such as in your first code, you should most definitely use forEach instead. - anyone
  • Object.fromEntries is ES2019, not ES2015. Also, as others have said, I'd highly recommend replacing the .map in the first snippet with forEach, or something else more appropriate than .map - anyone

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 can't 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.entries, 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. :-)

Answered   2023-09-21 08:11:51

  • Beautiful but I got caught by the fact that Object.keys doesn't enumerate inherited properties. I suggest you add a warning. - anyone
  • To shorten your answer, just use Object.entries({a: 1, b: 2, c: 3}). - anyone
  • You have some typos (you refer to (o, f) as arguments but use obj in the body. - anyone
  • Hey, can you provide more information about why we should avoid inheritance? Some good article would be enough :) - anyone
  • The solution Object.assign(...Object.entries(obj).map(([k, v]) => ({[k]: v * v}))) does not work if obj is an empty object. Change to: Object.assign({}, ...Object.entries(obj).map(([k, v]) => ({[k]: v * v}))). - anyone

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 }

Answered   2023-09-21 08:11:51

  • There is no need to add an extra HTTP call and an extra library just for one function. In any case, this answer is now outdated and you can simply call Object.entries({a: 1, b: 2, c: 3}) to get an array. - anyone
  • Why is getting an array useful? The requirement was for a mapped object. Also there’s no implied HTTP call in using Lodash, a popular library essentially built for this type of thing, although there’s quite a few things that ES6 has precluded the necessity of using utility function libraries to some degree lately. - anyone
  • extra HTTP call to pull Lodash, I guess. If this is your only use case, indeed it's an overkill. Nonetheless, it makes sense to have this answer around for Lodash is such a widespread library. - anyone
  • not to mention you should actually use _.map() so you get the key as the second argument - as required by the OP. - anyone
  • _.mapValues() does also provide the key as the 2nd argument. Also _.map() would not work here as it only returns arrays, not objects: _.map({ 'a': 1, 'b': 2, 'c': 3}, n => n * 3) // [3, 6, 9] - anyone

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.

Answered   2023-09-21 08:11:51

  • Ok. :) A comment on this question brought me here. I'll +1 this since the accepted answer is clearly misusing map, but I must say that modifying Object.prototype doesn't sit well with me, even if it isn't enumerable. - anyone
  • @JLRishe Thanks. IMHO in ES5 there's really no longer any reason not to modify Object.prototype other than the (theoretical) risk of collision with other methods. FWIW, I can't understand how the other answer got as many votes as it has, it's completely wrong. - anyone
  • Yeah, collisions were what I had in mind, especially with a name like map. - anyone
  • This already doesn't work: o = {map: true, image: false}. You're risking it just to write o.map(fn) instead of map(o,fn) - anyone
  • @bfred.it and I've updated accordingly. I'd note that this only removes the risk of clashing with a property of that same name. I checked, and there's so few properties on Object that I think if ES ever did acquire this method it would be Object.map rather than Object.prototype.map (and this is also consistent with the other "static" methods on Object) - anyone

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.

Answered   2023-09-21 08:11:51

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:

const 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

Answered   2023-09-21 08:11:51

  • Why do you add this function to the global Object object? Just have const mapObject = (obj, fn) => { [...]; return ret; }. - anyone
  • Because it should be a method on Object :) - anyone
  • As long as we don't mess with Object.prototype then we should be ok - anyone
  • If map were just a random vague thing, sure. But .map is generally understood as a Functor interface, and there's no single definition of Functor for "Object" because virtually anything in javascript can be an Object, including things with their own very distinct and defined .map interfaces/logic. - anyone
  • In my opinion first argument of callback should be iterated element itself, not a key. For example i assume it should give me same object, as it usualy happen with common map : Object.map({prop:1}, el => el) but it returns keys with value of same key name... - anyone

Minimal version

ES2017

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

ES2019

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

Answered   2023-09-21 08:11:51

  • I think this is incorrect because of a typo, I think you mean => Object.entries(obj).reduce((a, [k, v]) => [a[k] = v * v, a], {}), angled-brackets instead of parentheses. - anyone
  • @AlexanderMills, my code is correct. Read more about comma operator inside parentheses : developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - anyone
  • basically, my code is equivalent to: Object.entries(obj).reduce((a, [k, v]) => {a[k] = v * v; return a}, {}) - anyone
  • Webstorm warns the developer of usage of "comma expressions" saying that they "are normally the sign of overly clever code" ... lol just sayin' - anyone
  • And he's right. for a more understandable code, use loop: stackoverflow.com/a/14810722/806169 - anyone

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

Answered   2023-09-21 08:11:51

  • This doesn't remotely work - it just returns an array of the values of the object, not a new object. I can't believe it has this many up-votes. - anyone
  • You are correct, it does not answer the question correctly as they were looking for an answer for mapping an object to and object. I came here looking for an answer for mapping an object to an array and got this page as a result, so I will leave my answer and edit it to reflect that it is an alternate answer for people who may have gotten here as a result of looking for mapping an object to arrays. - anyone
  • In ES7 that'll trivially be Object.values(myObject) - anyone
  • const obj = { foo: 'bar', baz: 42 }; console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ] - anyone
  • This doesn't work, just outputs an array with the object values - anyone

JavaScript just got the new Object.fromEntries method.

Example

function mapObject (obj, fn) {
  return Object.fromEntries(
    Object
      .entries(obj)
      .map(fn)
  )
}

const myObject = { a: 1, b: 2, c: 3 }
const myNewObject = mapObject(myObject, ([key, value]) => ([key, value * value]))
console.log(myNewObject)

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

Answered   2023-09-21 08:11:51

  • Basically, Object.fromEntries is the opposite of Object.entries. Object.entries converts an object to a list of key-value pairs. Object.fromEntries converts a list of key-value pairs to an object. - anyone
  • Not a bad solution. Clean and simple. Except function params are different to Array.map(). My preference would be for the map function params to be (value, key). I know this seems somewhat backwards, however that's the order used for Array.map() and Array.forEach() so it's more consistent. - anyone

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.

// small, reusable auxiliary functions

const keys = o => Object.keys(o);

const assign = (...o) => Object.assign({}, ...o);

const map = f => xs => xs.map(x => f(x));

const mul = y => x => x * y;

const sqr = x => mul(x) (x);


// the actual map function

const omap = f => o => {
  o = assign(o); // A
  map(x => o[x] = f(o[x])) (keys(o)); // B
  return o;
};


// mock data

const o = {"a":1, "b":2, "c":3};


// and run

console.log(omap(sqr) (o));
console.log(omap(mul(10)) (o));

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

Answered   2023-09-21 08:11:51

  • Looks like a bit over engineered; I count 6 functions for what's essentially a loop. Other solutions are far simpler and the accepted answer is 5 times faster too. - anyone
  • @bfred.it What is the purpose of your comment? If you like micro-optimization you shouldn't use Array.prototype.reduce either. All I want to illustrate here is that the accepted answer somehow "abuses" Array.prototype.reduce and how a purely functional mapping could be implemented. If you're not interested in functional programming, just ignore my answer. - anyone
  • If you're not interested in performance and simplicity, don't read my comment then. :) A lot of features are "abused" but sometimes they fit the abuse better than other solutions. - anyone
  • "reducing means to change the structure of a composite type" I don't think that's true. An Array.reduce that produces a new array of the exact same length or even the exact same values is perfectly legitimate. Reduce can be use to re-create the functionality of map and/or filter (or both, as in a complex transducer, for which reduce is the basis). In FP, it's a type of fold, and a fold that ends up with the same type is still a fold. - anyone
  • @Dtipson You're absolutely right. A fold is more generic than a map (functor). However, this was my knowledge from mid-2016. That's half an eternity :D - anyone

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.

Answered   2023-09-21 08:11:51

  • How about using Destructing? - anyone
  • @K._ it used to be very slow, but I don't know about performance now. It looks like V8 v 5.6 introduced some optimisations for destructuring but that must be measured v8project.blogspot.co.uk - anyone
  • Or, less performant es7 but immutable: const fn = v => v * 2; const newObj = Object.entries(myObject).reduce((acc, [k,v]) => Object.assign({}, acc, {[k]: fn(v)}), {}); - anyone

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

You can convert the object values to an array:

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

let valuesArray = Object.values(myObject);

console.log(valuesArray);

You can convert the object keys to an array:

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

let keysArray = Object.keys(myObject);

console.log(keysArray);

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

Answered   2023-09-21 08:11:51

  • In 2020, I think this should be the accepted answer. - anyone

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}

Answered   2023-09-21 08:11:51

  • Where $ is jquery? - anyone
  • Yes you can use both $ and jQuery - anyone
  • @Ronald i have misunderstood, see my updated answer, thanks for not downvoting but truly making aware to my mistake, thanks for improving community. - anyone
  • @bcoughlan yes it is exactly which i have written in comment too, it is squaring the numbers, what do you want then? - anyone
  • @HaritsinhGohil I took it to mean that he was criticizing you for giving a jQuery solution. It's true that there is some impetus these days to move away from jQuery, and of course there is Node, but unless an OP asks specifically for pure JS or Node, I think it's fine to assume someone is working in a web environment and that jQuery is almost certain to be available. - anyone

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

Answered   2023-09-21 08:11:51

  • Perfomance issues: typeof callback === 'function' absolutely redundant. 1) map has no meaning without callback 2) if callback isn't function, yours map implementation just runs meaningless for-loop. Also, Object.prototype.hasOwnProperty.call( obj, key ) is a bit overkill. - anyone

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 {}.

const identity = x =>
  x
  
const mapReduce = (m, r) =>
  (a, x) => r (a, m (x))

const omap = (f = identity, o = {}) =>
  Object
    .keys (o)
    .reduce
      ( mapReduce
          ( k => ({ [k]: f (o[k]) })
          , Object.assign
          )
      , {}
      )
          
const square = x =>
  x * x
  
const data =
  { a : 1, b : 2, c : 3 }
  
console .log (omap (square, data))
// { a : 1, b : 4, c : 9 }

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.

Answered   2023-09-21 08:11:51

  • Let us rather use Map and Map.entries, OK :D. I'm tired of abusing plain objects as map data types. - anyone
  • I agree Map should be used where/when possible, but it does not totally replace the need to use these procedures on plain JS objects tho :D - anyone
  const array = Object.keys(object)
  //returns all keys as array ["key", "key"]

  const array = Object.values(object)
  //returns all values as array ["value", "value"]

  const array = Object.entries(object)
  //returns all entries as array = [["key","value"], ["key","value"]]

Use Map on the result.

  array.map()

Answered   2023-09-21 08:11:51

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}

Answered   2023-09-21 08:11:51

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/

Answered   2023-09-21 08:11:51

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.

Answered   2023-09-21 08:11:51

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.

Answered   2023-09-21 08:11:51

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

Answered   2023-09-21 08:11:51

This is my way to do it and results to be worth in terms of efficiency and readability.

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

const newObject = Object.entries(myObject)
  .map(([key, value]) => `${key}: ${value * value}`)
  .join(', ');

console.log(newObject)

Answered   2023-09-21 08:11:51

  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center. - anyone

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)

Answered   2023-09-21 08:11:51

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 }

Answered   2023-09-21 08:11:51

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.

Answered   2023-09-21 08:11:51

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:

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

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

newObject = myObject.map(function (value, label) {
  return value * value;
});
console.log("newObject is now",newObject);
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).

Answered   2023-09-21 08:11:51

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

Answered   2023-09-21 08:11:51

I handle only strings to reduce exemptions:

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

Answered   2023-09-21 08:11:51

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 }

Answered   2023-09-21 08:11:51

  • If ever useful for anyone: npm install @mattisg/object.map. - anyone

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

Answered   2023-09-21 08:11:51