我试图使用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)
您可以使用reduce with Array Destructuring。
bookpriceObj = bookprice.reduce((a, [b, c]) => (a[b] = c, a), {});
这是发生了什么:
a
是累加器,它具有传递给reduce
的最终参数的初始值。我们传递的最后一个值是{}
,所以它是一个对象[a, b] = ["one", "two"]
指定a
的值为"one"
和b
,其值为"two"
b
(a.e。“book1”)的值赋值为对象的属性(a
),并给它一个等于c
的值(a.e。“$ 2”)reduce
的每次迭代你必须返回累加器(a
)bookpriceObj
结果!var bookprice = [ ["book1", "$5"], ["book2", "$2"], ["book3", "$7"]],
bookpriceObj = bookprice.reduce((a, [b, c]) => (a[b] = c, a), {});
console.log(bookpriceObj)
您需要从“reducer”AKA返回一个对象,即reduce的第一个参数,并使用空对象作为第二个参数。
var bookprice = [
["book1", "$5"],
["book2", "$2"],
["book3", "$7"]
];
var result = bookprice.reduce(function(object, el) {
object[el[0]] = el[1]
return object;
}, {})
console.log(result)
您不需要for循环,因为reduce已遍历数组。
使用Array.reduce()
,Array destructuration
,Dynamical keys
和Spread operator
。
const bookprice = [
['book1', '$5'],
['book2', '$2'],
['book3', '$7'],
];
const ret = bookprice.reduce((tmp, [
name,
price,
]) => ({
...tmp,
[name]: price,
}), {});
console.log(ret);
您没有在reduce函数中返回累积的对象,并且不需要for循环。
尝试:
const bookprice = [["book1", "$5"], ["book2", "$2"], ["book3", "$7"]];
const nameIndex = 0;
const priceIndex = 1;
const bookPricesObj = bookprice.reduce((prices, bookInfo) => {
const name = bookInfo[nameIndex];
const price = bookInfo[priceIndex];
prices[name] = price;
return prices;
}, {});
bookprice.reduce((acc, price) => {
let tmp = {}
tmp[price[0]] = price[1]
return Object.assign(acc, tmp)
}, {})
使用Array.prototype.reduce将嵌套数组转换为对象
var bookprice = [
["book1", "$5"],
["book2", "$2"],
["book3", "$7"]
];
bookpriceObj = bookprice.reduce(function(acc, cur, i) {
acc[cur[0]] = cur[1];
return acc;
}, {})
console.log(bookpriceObj);