将嵌套数组转换为对象

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)

  • @GrégoryNEUT我知道,但在这种情况下,我不是减少粉丝的忠实粉丝,最终价值是一个对象,而不是一个单一的价值(这就是目的).我认为使用循环更清楚.在我看来,reduce()最好减少,找到一个单独的值作为最终值. (2认同)