代码之家  ›  专栏  ›  技术社区  ›  Costin

节点.js基于其值返回对象键

  •  0
  • Costin  · 技术社区  · 6 年前

    节点8.10

    例子

    // I do not like this solution, there is a 2 line body
    // `c` may be undefined or a string (for example)
    const f = (a, b, c) => {
      if (c) return ({ a, b, c });
      else return { a, b }
    }
    

    c 根据其价值包括或排除? 我希望这样:

    // I expect this kind of solution.
    const f = (a, b, c) => ({ a, b, ___????___ })
    
    1 回复  |  直到 6 年前
        1
  •  3
  •   Nicolas    6 年前

    const f = (a, b, c) => (c ? { a, b, c } : { a, b });
    

    const f = (a, b, c) => {
      const result = { a, b };
      if (c) result.c = c;
      return result;
    }