In Javascript a dictionary comprehension, or an Object `map` In Javascript a dictionary comprehension, or an Object `map` python python

In Javascript a dictionary comprehension, or an Object `map`


Assuming a_list is an Array, the closest would probably be to use .reduce().

var result = a_list.reduce(function(obj, x) {    obj[key_maker(x)] = val_maker(x);    return obj;}, {});

Array comprehensions are likely coming in a future version of JavaScript.


You can patch non ES5 compliant implementations with the compatibility patch from MDN.


If a_list is not an Array, but a plain object, you can use Object.keys() to perform the same operation.

var result = Object.keys(a_list).reduce(function(obj, x) {    obj[key_maker(a_list[x])] = val_maker(a_list[x]);    return obj;}, {});


Here's a version that doesn't use reduce:

Object.fromEntries( a_list.map( x => [key_maker(x), value_maker(x)]) );

Object.fromEntries is basically the same as _.fromPairs in Lodash. This feels the most like the Python dict comprehension to me.


Old question, but the answer has changed slightly in new versions of Javascript. With ES2015 (ES6) you can achieve a one-liner object comprehension like this:

a_list.reduce((obj, x) => Object.assign(obj, { [key_maker(x)]: value_maker(x) }), {})