Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to not include field in object if value is undefined

Tags:

javascript

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.

like image 914
D.Mark Avatar asked Aug 22 '18 05:08

D.Mark


2 Answers

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;
};
like image 195
UtkarshPramodGupta Avatar answered Sep 20 '22 01:09

UtkarshPramodGupta


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 }

like image 32
Anh Pham Avatar answered Sep 23 '22 01:09

Anh Pham