1

Im writing a small application i Angular2, and need a simple way to convert a list to a dict.

I have a list:

var list = ["foo", "bar"];

I want to convert the list to a dict like this:

var dict = {foo: "foo", bar: "bar"};

Whats the easiest way to do this using typescript, javascript, jQuery or Angular2?

Vingtoft
  • 13,368
  • 23
  • 86
  • 135

2 Answers2

2

Try with Array#reduce

var list = ["foo", "bar"];
console.log(list.reduce((a,b)=> (a[b]=b , a), {}))
prasanth
  • 22,145
  • 4
  • 29
  • 53
1
let list = ["foo", "bar"];

        let dict = {};
        for (let i=0; i< list.length; i++ ) {
                dict[list[i]] = list[i];
        }
        console.log(dict);
Amit Chigadani
  • 28,482
  • 13
  • 80
  • 98