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

前端 未结 6 1422
青春惊慌失措
青春惊慌失措 2020-12-28 13:01

I need to generate a couple of objects from lists in Javascript. In Python, I\'d write this:

{key_maker(x): val_maker(x) for x in a_list}

A

6条回答
  •  感动是毒
    2020-12-28 13:27

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

提交回复
热议问题