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

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; 

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.