【发布时间】:2017-12-24 05:11:57
【问题描述】:
如何使用 .reduce() 将多维数组转换为对象数组?
起始数组
[
[
['juice', 'apple'], ['maker', 'motts'], ['price', 12]
],
[
['juice', 'orange'], ['maker', 'sunkist'], ['price', 11]
]
]
结束数组
[
{juice: 'apple', maker: 'motts', price: 12},
{juice: 'orange', maker: 'sunkist', price: 11}
]
这就是我现在所拥有的。这真的只是我在黑暗中拍摄。
var transformData = (array) => {
var newArray = array.push(function (all, item, index) {
var newItem = item.reduce(function (all, item, index) {
all[item[0]] = item[1]
return all
}, {})
return all
}, [])
newArray.push(newItem)
return newArray
}
【问题讨论】:
-
你意识到你正在将函数推送到新数组中
-
尝试
array.map而不是`array.push(` -
奇怪的是你认为 array.push 像 array.reduce 一样工作:p
标签: javascript arrays object functional-programming