0

How can I an array of functions to an object with keys as functions' name and values as functions' return values. An example would be:

 var a=x=>"M",b=_=>"e",c=_=>"r",d=_=>"y",e=_=>"C",
     f=_=>"h",g=_=>"i",h=_=>"s",i=_=>"t",j=_=>"m",
     k=_=>"a",l=_=>" ",m=_=>"!",
     funcs = [a,b,c,d,e,f,g,h,i,j,k,l,m]

 // do some magic with funcs to receive myDict     
 var myDict = {'a':'M', 'b':'e', 'c':'r', 'd':'y', ...}

I tried something like this but it didn't work.

var dict = funcs.reduce(function (acc, func) {
    acc[func.name] = func();
    return acc;
}, {});

How can I fix this to achieve the wanted result? Is there a better without using reduce?

Huy Tran
  • 1,770
  • 3
  • 21
  • 41

4 Answers4

2

Loop over the array of functions funcs, get the name of the function using funcs[i].name and return value of that function by funcs[i]().

Store name as key and return value as value of that key in an object.

var a=x=>"M",b=_=>"e",c=_=>"r",d=_=>"y",e=_=>"C",
    f=_=>"h",g=_=>"i",h=_=>"s",i=_=>"t",j=_=>"m",
    k=_=>"a",l=_=>" ",m=_=>"!";

var funcs = [a,b,c,d,e,f,g,h,i,j,k,l,m];

var dict = (function (funcs) {
    var dict = {};
    for(var i=0; i<funcs.length; i++){
     var name = funcs[i].name;
     var ret = funcs[i]();
      dict[name] = ret;
    }
    return dict;
})(funcs);

console.log(dict);
vatz88
  • 2,422
  • 2
  • 14
  • 25
1

instead of reduce, you could do something like this

var dict = {}
funcs.forEach(function (func) {
  dict[func.name] = func();
});

and the fiddle: https://jsfiddle.net/jperelli/0tpj88ab/

jperelli
  • 6,988
  • 5
  • 50
  • 85
0

I'm just being silly and forget to return a value at the end of a function. So my proposed solution with reduce from the beginning is actually correct.

var dict = funcs.reduce(function (acc, func) {
    acc[func.name] = func();
    return acc;
}, {});
Huy Tran
  • 1,770
  • 3
  • 21
  • 41
0

You could use a combination of Object.assign and Array#map.

var a = x => "M", b = _ => "e", c = _ => "r", d = _ => "y", e = _ => "C", f = _ => "h", g = _ => "i", h = _ => "s", i = _ => "t", j = _ => "m", k = _ => "a", l = _ => " ", m = _ => "!",
    funcs = [a, b, c, d, e, f, g, h, i, j, k, l, m],
    myDict = Object.assign(...funcs.map(f => ({ [f.name]: f() })));

console.log(myDict);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392