请耐心回答我的愚蠢问题,我是javscript的新手。我正在尝试过滤地图,但无法将创建的对象分配给引用变量。
let serviceFeeMap = new Map();
paymentAmountServiceFeeInfo.map(serviceFees => {
if (serviceFees.serviceFees.serviceFeeApplicableMethods.length > 0) {
serviceFees.serviceFees.serviceFeeApplicableMethods.map(applicableMethod => {
let serviceFeeList = serviceFeeMap.get(applicableMethod);
if (!serviceFeeList) {
serviceFeeMap.set(applicableMethod, new Array(serviceFees.serviceFees));
} else {
serviceFeeList.push(serviceFees.serviceFees);
serviceFeeMap.set(applicableMethod, serviceFeeList);
}
});
}
});
const finalResult = serviceFeeMap.forEach((v, k) => {
let values = v;
let count = 0;
const arrayValues = values.map((value) => {
if (count === 0) {
count++;
return {
applicableMethod : k,
serviceFeeAdjustmentType : value.serviceFeeAdjustmentType,
serviceFeeAmount : value.serviceFeeAmount
};
} else {
count++;
return {
applicableMethod : '',
serviceFeeAdjustmentType : value.serviceFeeAdjustmentType,
serviceFeeAmount : value.serviceFeeAmount
};
}
})
return arrayValues;
});
我得到的finalResult是未定义的。
答案 0 :(得分:1)
您正在尝试从forEach()
回调返回一个值,但是它不能返回任何值。 forEach()方法按插入顺序对Map对象中的每个键/值对执行一次提供的函数。
根据MDN documentation
forEach方法对实际存在的每个地图键执行一次提供的回调。对于已删除的密钥,不会调用它。但是,它针对存在但未定义的值执行。
这就是您获得undefined
中的finalResult
的原因。在这种情况下,您可以编写一个全局var
来保存Map.prototype.forEach()
let finalResult = [];
serviceFeeMap.forEach((v, k) => {
let values = v;
let count = 0;
const arrayValues = values.map((value) => {
if (count === 0) {
count++;
return {
applicableMethod : k,
serviceFeeAdjustmentType : value.serviceFeeAdjustmentType,
serviceFeeAmount : value.serviceFeeAmount
};
} else {
count++;
return {
applicableMethod : '',
serviceFeeAdjustmentType : value.serviceFeeAdjustmentType,
serviceFeeAmount : value.serviceFeeAmount
};
}
})
finalResult.push(arrayValues);
})
答案 1 :(得分:0)
这是因为forEach
将返回undefined
。您可以在map
内使用map
,这将返回arrys数组或在forEach
外部创建一个数组,并将arrayValues
推入其中。
const finalResult = serviceFeeMap.map((v, k) => {
let values = v;
let count = 0;
return values.map((value) => {
if (count === 0) {
count++;
return {
applicableMethod: k,
serviceFeeAdjustmentType: value.serviceFeeAdjustmentType,
serviceFeeAmount: value.serviceFeeAmount
};
} else {
count++;
return {
applicableMethod: '',
serviceFeeAdjustmentType: value.serviceFeeAdjustmentType,
serviceFeeAmount: value.serviceFeeAmount
};
}
})
});