I have the following function
const exampleFunction = (var1, var2, var3) => {
    return const targetObject = {
        var1,
        var2,
        var3,
    },
};
var2 and var3 are optional variables.
If all 3 variables were send to this function, then I need to return object with 3 fields.
If var2 is undefined, I need to return object with 2 fields only. If var3 is undefined, I need to return object with 2 fields only.
If var2 and var3 are undefined, I need to return object with 1 field only.
try this:
const exampleFunction = (var1, var2, var3) => {
    const targetObject = {};
    if (var1) targetObject.var1 = var1;
    if (var2) targetObject.var2 = var2;
    if (var3) targetObject.var3 = var3;
    return targetObject;
};
                        Use JSON.parse together with JSON.stringify since JSON.stringify will skip undefined, Function, and Symbol during the conversion. If those types are in an array, they will be automatically censored to null in that array by JSON.stringify.
const exampleFunction = (var1, var2, var3) => JSON.parse(JSON.stringify({
  var1,
  var2,
  var3
}))
const outputs = exampleFunction(undefined, 2, undefined)
console.log(outputs)
Outputs: { var2: 2 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With