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
Mirza Andriamanamisoa
4215 silver badges17 bronze badges
1 Answer 1
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
joy08
9,6729 gold badges43 silver badges81 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js