bjfletcher
bjfletcher

Reputation: 11518

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;

Upvotes: 3

Views: 1210

Answers (1)

mido
mido

Reputation: 25054

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

Upvotes: 2

Related Questions