Conditional object declaration in javascript

Viewed 78

I have an object that can have 2 attributes, "a" and "b". Attributes "a" === "fixed", always, while "b" must be set depending on some variables values. These variables are "c" (boolean) and "d" (string).

If c is false the object must be:

const obj = {a: "fixed", b: "cFalse"}

If c is true and d is an empty string the object must be:

const obj = {a: "fixed", b: "cTrueDEmpty"}

while if c is true and d is not empty the object must be:

const obj = {a: "fixed", b: "cTrueDNotEmpty"}

I'm having troubles to code this in javascript, I tried with a ternary operator but linter says it's too complicated:

const obj= {
a: "fixed",
...(c === false ? {b: "cFalse"} : (d === "" ? {b: "cTrueDEmpty"} : {b: "cTrueDNotEmpty"} ) ),
};

Any suggestions? Thanks

3 Answers

You could take a nested conditional operator.

const getObject = (c, d) => ({
    a: 'fixed',
    b: c
        ? d 
            ? 'cTrueDNotEmpty'
            : 'cTrueDEmpty'
        : 'cFalse'
});

console.log(getObject(false));
console.log(getObject(true, ''));
console.log(getObject(true, 'xx'));

Try this :

const obj = {a: 'fixed', b: c ? (d ? 'cTrueDNotEmpty' : 'cTrueDEmpty') : 'cFalse' };

or (for the linter)

const dValueIfC = d ? 'cTrueDNotEmpty' : 'cTrueDEmpty'
const obj = {a: 'fixed', b: c ? dValueIfC : 'cFalse' };

JavaScript supports to do it without any ternal operators. If you want to do it in a one row and in the place of object declaration you can try this:

const obj = {a: 'fixed', b: c && (d && 'cTrueDNotEmpty' || 'cTrueDEmpty') || 'cFalse' };

Or in more readable way :

const bPropVal = c && (d && 'cTrueDNotEmpty' || 'cTrueDEmpty') || 'cFalse';
const obj = {a: 'fixed', b:bPropVal   };

NOTE: your string d can be null as well as empty

Related