我正在尝试使用reduce
将嵌套数组转换为对象。
我想转换var bookprice = [["book1", "$5"], ["book2", "$2"], ["book3", "$7"]];
至
var bookpriceObj = {
"book1": "$5",
"book2": "$2",
"book3": "$7"
};
这是我尝试过的
var bookprice = [["book1", "$5"], ["book2", "$2"], ["book3", "$7"]];
bookpriceObj = {};
bookprice.reduce(function(a, cv, ci, arr){
for (var i = 0; i < arr.length; ++i)
bookpriceObj [i] = arr[i];
return bookpriceObj ;
})
但是以下结果不是理想的结果
{
["book1", "$5"]
["book2", "$2"]
["book3", "$7"]
}
最佳答案
使用forEach更短
var bookprice = [["book1", "$5"], ["book2", "$2"], ["book3", "$7"]];
var bookpriceObj = {};
bookprice.forEach(e=>bookpriceObj[e[0]] = e[1]);
console.log(bookpriceObj)