Javascript:什么是将数组转换为对象的最佳方法?
问题描述:
最佳转换方式是什么:
a = ['USD', 'EUR', 'INR']
到
a = {'USD': 0, 'EUR': 0, 'INR': 0};
*将数组元素作为对象的键操作,其值最初为0。
*manipulating array element as key of objects with value as initially 0.
答
使用 数组#reduce
减少为单个对象的方法。
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);