olo*_*olo 6 javascript arrays javascript-objects
我试图用reduce嵌套数组转换为对象.
我想转换 var bookprice = [["book1", "$5"], ["book2", "$2"], ["book3", "$7"]];
至
var bookpriceObj = {
"book1": "$5",
"book2": "$2",
"book3": "$7"
};
Run Code Online (Sandbox Code Playgroud)
这是我试过的
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 ;
})
Run Code Online (Sandbox Code Playgroud)
但是以下结果并不是理想的结果
{
["book1", "$5"]
["book2", "$2"]
["book3", "$7"]
}
Run Code Online (Sandbox Code Playgroud)
Eme*_*eus 10
使用forEach更短
var bookprice = [["book1", "$5"], ["book2", "$2"], ["book3", "$7"]];
var bookpriceObj = {};
bookprice.forEach(e=>bookpriceObj[e[0]] = e[1]);
console.log(bookpriceObj)Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
263 次 |
| 最近记录: |