当它是数组时,当它不是数组时,如何映射响应?



我刚刚编写了两个简单的函数来验证一个字段是否有特定的值,但在某些情况下,响应可能是一个数组。我可以将这些函数简化为一个函数吗?我试着用同样的";isOrderInLastMile";当响应只是一个对象但我检索";map不是函数";错误

函数1:当响应是一个对象数组时,我使用这个函数。

export function isOrderInLastMile(pieces: any): boolean {
const totalPieces: number = pieces.length;
let momentFound: number = 0;
pieces.map((element) => {
if (
element.stagesHistory &&
getCurrentMoment(element.stagesHistory) ===
MomentsLabel.En_última_milla_id
) {
momentFound = momentFound + 1;
}
return momentFound;
});
return totalPieces === momentFound;
}

功能2:当这个响应只是一个对象时,我使用这个功能

export function isPieceInLastMile(piece: any): boolean {
return (
piece.stagesHistory &&
getCurrentMoment(piece.stagesHistory) === MomentsLabel.En_última_milla_id
);
}

如何统一这两个函数?谢谢!!!:(

将单个元素封装在数组中,如下所示:

export function isPieceInLastMile(piece: any): boolean {
return isOrderInLastMile([piece]);
}

或者在回调中使用单个函数

return pieces.every(isPieceInLastMile);

(可以使用后一个选项,而不是计算所有匹配的项目(

最新更新