我试图找出是否有办法将此代码重写为单个对象创建:
my_array = [ {key: 1,value: "foo"},{key: 2,value: "bar"} ]; let my_obj = {}; my_array.forEach((elem) => { my_obj[elem.key] = elem.value; });
我想做的是:
my_array = [ {key: 1,value: "bar"},]; const my_obj = ...?
有没有办法进行一次转换,相当于forEach调用?
解决方法
您可以使用
Array.prototype.reduce()
实现此目的:
var my_array = [{key: 1,value:"foo"},value:"bar"}]; var my_object = my_array.reduce(function(prev,curr) { prev[curr.key] = curr.value; return prev; },{}); console.log(my_object); // {"1": "foo","2": "bar"}
或者,使用ES6语法:
const my_object = my_array.reduce((prev,curr) => { prev[curr.key] = curr.value; return prev; },{});