我正在使用reduce函数,由于某种原因我在控制台上收到错误:
(index):77 Uncaught TypeError: filtered.push is not a function
DispatchedNumber
在映射到 Lines
数组之前应该存在。
function payload(order) {
return {
OrderId: order.ORDERID,
Lines: order.ITEMS.reduce(function(filtered, item) {
if (item.DispatchedNumber != undefined) {
var newItem = {
Qty: item.Qty,
QtyShipped: item.DispatchedNumber
}
filtered.push(newItem);
}
return filtered;
})
}
}
test = payload({
"ORDERID": 1233,
"ITEMS": [
{ Qty: 123, DispatchedNumber: 111 },
{ Qty: 111 },
{ Qty: 444, DispatchedNumber: 555 },
{ Qty: 443, DispatchedNumber: 323 }
]
})
用法:
console.log(JSON.stringify(test, null, 2));
最佳答案
reduce 函数中没有为累加器指定初始值。
请更新以下内容
order.ITEMS.reduce(function(filtered, item) {
if (item.DispatchedNumber != undefined) {
var newItem = {
Qty: item.Qty,
QtyShipped: item.DispatchedNumber
}
filtered.push(newItem);
}
return filtered;
}, []) // add the empty array (initial value of accumulator)
供引用,Array.reduce
关于javascript - Filtered.push 不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49999281/