Conditional spread element

后端 未结 5 2118
無奈伤痛
無奈伤痛 2021-02-19 03:50
const cond = false

const extraInfo = [
  {
    a: 11,
    b: 25
  },
  {
    a: 12,
    b: 34
  },
  {
    a: 1,
    c: 99
  }
]

const userInfo = [
  {
    z: 8
  },
          


        
5条回答
  •  别那么骄傲
    2021-02-19 04:09

    Another way:

    cond is true:

    var extraInfo = [
      {
        a: 11,
        b: 25
      },
      {
        a: 12,
        b: 34
      },
      {
        a: 1,
        c: 99
      }
    ]
    
    var cond = true;
    var userInfo = [
      {
        z: 8
      },
      {
        z: 10
      },
      ...(cond && extraInfo || [])
    ]
    console.log(userInfo);

    cond is false:

    var extraInfo = [
      {
        a: 11,
        b: 25
      },
      {
        a: 12,
        b: 34
      },
      {
        a: 1,
        c: 99
      }
    ]
    
    var cond = false;
    var userInfo = [
      {
        z: 8
      },
      {
        z: 10
      },
      ...(cond && extraInfo || [])
    ]
    console.log(userInfo);

提交回复
热议问题