是否存在使用javascript es6或es-next的语法来实现以下行为
let t = {
text: 'hello world',
[shouldShow ? ...{'show' : 'test text'} : ''],
test: 21
}
我希望如果shouldShow为true,则对象t应该为
{
text: 'hello world',
show: 'test text',
test: 21
}
并且如果shouldShow为false,则对象t为
{
text: 'hello world',
test: 21
}
我知道,我可以使用if / else来做到这一点,但我问是否只有一种语法可以用于一行代码
希望这可以解决:
如果在shouldShow为false的情况下希望显示属性存在,请尝试以下操作:
// 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
};
如果要从对象本身中删除它,请尝试此,
// 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;