Search code examples
javascriptfunctional-programmingecmascript-6ecmascript-harmony

Create a map with same values and keys the FP way using ES6/Harmony


Given a set of "Apple", "Banana", and "Orange", create the following:

{ "Apple": "Apple", "Banana": "Banana", "Orange": "Orange" }

that is, each string becomes the key as well as the value.

(That is, by the way, what Facebook's little KeyMirror JS utility does in their Flux examples.)

Is there a Functional Programming-style one-liner way of doing this using ES6/Harmony, e.g.:

["Apple", "Banana", "Orange"].map(v => v: v)

rather than a non-Functional Programming way of doing it, such as:

let o = {}; for (let v of ["Apple", "Banana", "Orange"]) o[v] = v;


Solution

  • how about this, .reduce((obj, str) => ({ ...obj, [str]: str }), {})

    for e.g :

    var arry = ["Apple", "Banana", "Orange"];
    var map = arry.reduce((obj, str) => ({ ...obj, [str]: str }), {});