0

is there a syntax with javascript es6 or es-next to achieve the following behavior

let t = {
 text: 'hello world',
 [shouldShow ? ...{'show' : 'test text'} : ''],
 test: 21
}

I want that if shouldShow is true the object t should be

{
 text: 'hello world',
 show: 'test text',
 test: 21
}

and if shouldShow is false the object t will be

{
 text: 'hello world',
 test: 21
}

I know, I can do that with if/else but I'm asking if there is a syntax that I can use for just one line of code

asked Feb 10, 2020 at 15:51
0

1 Answer 1

2

Hopefully this would solve :

In case you want the show property to be there when shouldShow is false, try this:

// this would give show:"" when shouldShow is false, else it will give show="test text"
let shouldShow = false;
let t = {
 text: "hello world",
 show: shouldShow ? "test text" : "",
 test: 21
}; 

In case you want it to be removed from the object itself then try this,

// this would make show="test text" when shouldShow is true else remove it from "t"
let shouldShow = true;
let t = {
 text: "hello world",
 test: 21
};
t = shouldShow ? { ...t, show: "test text" } : t; 
answered Feb 18, 2020 at 6:56
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.