3

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;

bjfletcher
  • 11,168
  • 4
  • 52
  • 67
  • 1
    fwiw, in Undescore/Lodash (with support down to ES3) — `var arr = ["Apple", "Banana", "Orange"]; _.object(arr, arr);` – kangax Dec 22 '14 at 14:20

1 Answers1

2

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 }), {});
mido
  • 24,198
  • 15
  • 92
  • 117
  • nice, thanks. :) There was me thinking that this wasn't possible yet. :) But this is a good answer. Looking forward to seeing performance metrics for this and for JS to have more FP methods like foldLeft/Right. – bjfletcher Dec 22 '14 at 09:15
  • 2
    `['Apple', 'Banana', 'Orange'].reduce((m, v) => { m[v] = v; return m; }, {})); // using the arrow function` – bjfletcher Dec 22 '14 at 09:23
  • Or using spread operator and returning object literal: `['Apple', 'Banana', 'Orange'].reduce((obj, str) => ({ ...obj, [str]: str }), {})` Terse but probably the worst performing option! – Jon Wyatt Jun 28 '21 at 19:48