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.
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.
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);
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);
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)
Use the Map
constructor:
new Map(a.map(x => [x, 0]))