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.

5
  • 2
    Define "best". Shortest code? Best performance? Least opportunities for nitpicking?
    – deceze
    Commented Jan 24, 2017 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. Commented Jan 24, 2017 at 11:27
  • I think this answer and this answer are right for you
    – Pine Code
    Commented Jan 24, 2017 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). Commented Jan 24, 2017 at 12:20

3 Answers 3

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);

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);

1
  • 3
    I think this is missing an object as the first argument? Object.assign({}, ...a.map(k => ({ [k]: 0 }))) Commented Feb 25, 2021 at 22:24
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)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.