我使用的是约简函数,而控制台上出现错误的原因如下:
(索引):77 TypeError: filtered.push不是一个函数
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));发布于 2018-04-24 10:25:48
还原函数中没有为累加器指定初始值。
请更新以下内容
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
发布于 2018-04-24 10:26:26
减少语法
arr.reduce(callback[, initialValue])您需要将filtered变量初始化为reduce()函数。
演示
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;
},[])
}
}
var 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));.as-console-wrapper { max-height: 100% !important; top: 0;}
https://stackoverflow.com/questions/49999281
复制相似问题