map function for objects (instead of arrays)
Javascriptnode.jsFunctional ProgrammingMap FunctionJavascript Problem Overview
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.)
Javascript Solutions
Solution 1 - Javascript
There is no native map
to the Object
object, but how about this:
var myObject = { 'a': 1, 'b': 2, 'c': 3 };
Object.keys(myObject).map(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))
Solution 2 - Javascript
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. :-)
Solution 3 - Javascript
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 }
Solution 4 - Javascript
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.
Solution 5 - Javascript
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.
Solution 6 - Javascript
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
Solution 7 - Javascript
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];
});
Solution 8 - Javascript
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).
Solution 9 - Javascript
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]))
↑↑↑↑↑
Solution 10 - Javascript
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 ofo
is generated. We are now able to mutateo
withinomap
without mutatingo
in the parent scope. - In line B
map
's return value is ignored, becausemap
performs a mutation ofo
. Since this side effect remains withinomap
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.
Solution 11 - Javascript
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
Solution 12 - Javascript
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.
Solution 13 - Javascript
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}
Solution 14 - Javascript
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;
});
Solution 15 - Javascript
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
m
, the mapping function – gives you a chance to transform the incoming element before…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.
Solution 16 - Javascript
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.
Solution 17 - Javascript
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:
Solution 18 - Javascript
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}
Solution 19 - Javascript
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.
Solution 20 - Javascript
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
Solution 21 - Javascript
If you're interested in map
ping 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 }
Solution 22 - Javascript
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)
Solution 23 - Javascript
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 }
Solution 24 - Javascript
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.
Solution 25 - Javascript
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);
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
).
Solution 26 - Javascript
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(...)
Solution 27 - Javascript
I handle only strings to reduce exemptions:
Object.keys(params).map(k => typeof params[k] == "string" ? params[k] = params[k].trim() : null);
Solution 28 - Javascript
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];
}
}
}
}
}
Solution 29 - Javascript
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
const 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('back to json:', JSON.parse(json))
Solution 30 - Javascript
I needed a function to optionally map not only (nor exclusively) values, but also keys. The original object should not change. The object contained only primitive values also.
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;
}
Use. Pass a keymapper and a valuemapper function:
const o1 = { x: 1, c: 2 }
mappedObject(o1, k => k + '0', v => v + 1) // {x0: 2, c0: 3}
Solution 31 - Javascript
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();
Solution 32 - Javascript
var myObject = { 'a': 1, 'b': 2, 'c': 3 };
Object.keys(myObject).filter((item) => myObject[item] *= 2)
console.log(myObject)
Solution 33 - Javascript
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 }
Solution 34 - Javascript
Here is another version that allows the mapping function to declare any number of new properties (keys and values) based on the current key and value. E: Now works with arrays too.
Object.defineProperty(Object.prototype, 'mapEntries', {
value: function(f,a=Array.isArray(this)?[]:{}) {
return Object.entries(this).reduce( (o, [k,v]) =>
Object.assign(o, f(v, Array.isArray(a)?Number(k):k, this)),
a);
}
});
const data = { a : 1, b : 2, c : 3 };
const calculate = (v, k) => ({
[k+'_square']: v*v,
[k+'_cube']: v*v*v
});
console.log( data.mapEntries( calculate ) );
// {
// "a_square": 1, "a_cube": 1,
// "b_square": 4, "b_cube": 8,
// "c_square": 9, "c_cube": 27
// }
// Demonstration with an array:
const arr = [ 'a', 'b', 'c' ];
const duplicate = (v, i) => ({
[i*2]: v,
[i*2+1]: v+v
});
console.log( arr.mapEntries( duplicate ) );
// [ "a", "aa", "b", "bb", "c", "cc" ]
Solution 35 - Javascript
const orig = { 'a': 1, 'b': 2, 'c': 3 }
const result = _.transform(orig, (r, v, k) => r[k.trim()] = v * 2);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Use new _.transform() to transforms object.
Solution 36 - Javascript
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)
Solution 37 - Javascript
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' ]
Solution 38 - Javascript
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), {})
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);
Solution 39 - Javascript
Async, anyone?
Despite of the large number of comments, I didn't find a solution for using an async
mapper. Here's mine.
Uses p-map, a trusted (@sindresorhus) and small dependency.
(note that no options are passed to p-map
. Refer to the docs if you need to adjust concurrency/error handling).
Typescript:
import pMap from "p-map";
export const objectMapAsync = async <InputType, ResultType>(
object: { [s: string]: InputType } | ArrayLike<InputType>,
mapper: (input: InputType, key: string, index: number) => Promise<ResultType>
): Promise<{
[k: string]: ResultType;
}> => {
const mappedTuples = await pMap(
Object.entries(object),
async ([key, value], index) => {
const result = await mapper(value, key, index);
return [key, result];
}
);
return Object.fromEntries(mappedTuples);
};
Plain JS:
import pMap from "p-map";
export const objectMapAsync = async (
object,
mapper
) => {
const mappedTuples = await pMap(
Object.entries(object),
async ([key, value], index) => {
const result = await mapper(value, key, index);
return [key, result];
}
);
return Object.fromEntries(mappedTuples);
};
};
Usage example:
(highly contrived, no error handling, no types)
// Our object in question.
const ourFavouriteCharacters = {
me: "luke",
you: "vader",
everyone: "chewbacca",
};
// An async function operating on the object's values (in this case, strings)
const fetchCharacter = (charName) =>
fetch(`https://swapi.dev/api/people?search=${charName}`)
.then((res) => res.json())
.then((res) => res.results[0]);
// `objectMapAsync` will return the final mapped object to us
// (wrapped in a Promise)
objectMapAsync(ourFavouriteCharacters, fetchCharacter).then((res) =>
console.log(res)
);