Quiero asignar un valor a la propiedad al crear un objeto basado en muchas condiciones. Actualmente estoy usando una función separada para obtener el valor de la propiedad, algo como esto:
function getLocationId(currency, storeCode, isBundle) { if (currency === 'MYR') { if (storeCode === 'store-1') { return 1; } else if (storeCode === 'store-2') { return 2; } } else if (currency === 'SGD') { if (storeCode === 'store-1') { return 3; } else if (storeCode === 'store-2') { // This function can return the same value for a different condition return 2; } else if (!storeCode && !isBundle) { return 8; } } . . . // More conditions, with some involving `isBundle` } function getAccountId(currency, storeCode, paymentMethod) { // Function definition similar to getLocationId // with checks for currency, storeCode, paymentMethod } function getRequestObject(event) { return { . . . location: getLocationId(event.currency, event.storeCode, event.item.isBundle), account: getAccountId(event.currency, event.storeCode, event.paymentMethod), . . . }; } Siento que hay muchas construcciones if...else usadas con cheques anidados nuevamente. ¿Hacer eso es incluso una buena idea? ¿Hay algún patrón de diseño que pueda usar para crear un objeto de solicitud con el ID de ubicación y el ID de cuenta correctos en función del event de parámetro en getRequestObject ?
PD: no devuelvo el valor entero en el código base real, sino que uso esta biblioteca llamada node-config y almaceno estos ID en un archivo JSON que luego puedo recuperar con config.get('propertyName') .
Un enfoque un poco más limpio sin sentencias else después de las sentencias return .
function getLocationId(currency, storeCode, isBundle) { if (currency === 'MYR') { if (storeCode === 'store-1') return 1; if (storeCode === 'store-2') return 2; // other if or return a default value for this currency } if (currency === 'SGD') { if (storeCode === 'store-1') return 3; if (storeCode === 'store-2') return 2; if (!storeCode && !isBundle) return 8; } }