【问题标题】:Dynamic object property javascript动态对象属性 javascript
【发布时间】:2020-05-25 23:27:27
【问题描述】:

是否有 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 做到这一点,但我想问是否有一种语法可以只用于一行代码

【问题讨论】:

    标签: ecmascript-next ecmascript-2016


    【解决方案1】:

    希望这能解决:

    如果您希望 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; 
    
    

    【讨论】:

      猜你喜欢
      • 2021-09-26
      • 1970-01-01
      • 2013-07-21
      • 2020-07-08
      • 1970-01-01
      • 2010-10-07
      • 2019-11-14
      • 2018-07-06
      相关资源
      最近更新 更多