12

what is the best way to convert:

a = ['USD', 'EUR', 'INR']

to

a = {'USD': 0, 'EUR': 0, 'INR': 0};

*manipulating array element as key of objects with value as initially 0.

Shishir Sonekar
  • 410
  • 1
  • 3
  • 15
  • 2
    Define "best". Shortest code? Best performance? Least opportunities for nitpicking? – deceze Jan 24 '17 at 11:26
  • This really isn't enough information to go on. Why can't you do this manually, is this procedural data, is there a consistent value you want assigned to each variable in the object, etc. – Liam MacDonald Jan 24 '17 at 11:27
  • http://stackoverflow.com/questions/4215737/convert-array-to-object – Nitin Dhomse Jan 24 '17 at 11:28
  • I think [this answer](http://stackoverflow.com/questions/4215737/convert-array-to-object) and [this answer](http://stackoverflow.com/questions/32002176/how-to-convert-array-to-object-in-javascript) are right for you – Pine Code Jan 24 '17 at 11:40
  • @deceze looking for both in terms of short code and performance.. but the main emphasis is on using best manipulation function(for this condition). – Shishir Sonekar Jan 24 '17 at 12:20

3 Answers3

24

Use Array#reduce method to reduce into a single object.

a = ['USD', 'EUR', 'INR'];

console.log(
  a.reduce(function(obj, v) {
    obj[v] = 0;
    return obj;
  }, {})
)

Or even simple for loop is fine.

var a = ['USD', 'EUR', 'INR'];
var res = {};

for (var i = 0; i < a.length; i++)
  res[a[i]] = 0;

console.log(res);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
17

You could use Object.assign with Array#map and spread syntax ...

var array = ['USD', 'EUR', 'INR'],
    object = Object.assign(...array.map(k => ({ [k]: 0 })));

console.log(object);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
5

You can use a Array.map and Object.assign

var a = ['USD', 'EUR', 'INR']
var result = Object.assign.apply(null, a.map(x =>({[x]:0})));
console.log(result)
Vladu Ionut
  • 8,075
  • 1
  • 19
  • 30