3

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 3

1

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'));

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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' };

1 Comment

My linter says "Exract this nested ternary operation into an independent statement." Referring to (d !== '' ? 'cTrueDNotEmpty' : 'cTrueDEmpty'). How can I?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.