Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ecmascript next 动态对象属性javascript_Ecmascript Next_Ecmascript 2016 - Fatal编程技术网

Ecmascript next 动态对象属性javascript

Ecmascript next 动态对象属性javascript,ecmascript-next,ecmascript-2016,Ecmascript Next,Ecmascript 2016,javascript es6或es next是否有语法来实现以下行为 let t = { text: 'hello world', [shouldShow ? ...{'show' : 'test text'} : ''], test: 21 } 我想如果shouldShow是真的,那么对象t应该是真的 { text: 'hello world', show: 'test text', test: 21 } 如果shouldShow为false

javascript es6或es next是否有语法来实现以下行为

let t = {
    text: 'hello world',
    [shouldShow ? ...{'show' : 'test text'} : ''],
    test: 21
}
我想如果shouldShow是真的,那么对象t应该是真的

{
    text: 'hello world',
    show: 'test text',
    test: 21
}
如果shouldShow为false,则对象t将为

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

我知道,我可以用if/else实现这一点,但我想问的是,是否有一种语法可以只用于一行代码

如果希望show属性在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; 


希望这能解决:

如果希望show属性在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;