项目作者: lukem512

项目描述 :
A proposal for conditional properties when defining ECMAScript objects
高级语言:
项目地址: git://github.com/lukem512/proposal-condition-property-definitions.git


Condition Property Definitions for ECMAScript

This proposal introduces an operator for defining conditional properties in ECMAScript objects. This operator allows properties to be included if a specific condition evaluates to true.

The operator can be used to add a single property subject to a condition.

  1. let obj = {
  2. cond ? prop: value
  3. };

The operator can also be used to add multiple properties subject to a single condition; this is achieved by declaring the properties within a block.

  1. let obj = {
  2. cond ? {
  3. prop1: value1,
  4. prop2: value2
  5. }
  6. };

Multiple conditions can also be combined within parenthesis to create more complex conditions for including properties.

  1. let obj = {
  2. (cond1 && cond2) ? prop: value
  3. };

Motivation for Use

The use case for this operator is that there is often a need to add a property if and only if a certain condition is satisfied. This requires the object to be assigned to a variable and for a conditional statement to be used, resulting in several additional lines of code.

  1. function(cond) {
  2. let obj = {
  3. x: 14,
  4. y: 39
  5. };
  6. if (cond) {
  7. obj.prop = true;
  8. }
  9. return obj;
  10. }

By using the operator proposed in this document, the function definition can be simplified.

  1. function(cond) {
  2. return {
  3. x: 14,
  4. y: 39,
  5. cond ? prop: true
  6. };
  7. }

Existing Solutions

This behaviour can be obtained using the spread operator in tandem with the ternary operator within the object definition. This is effective but requires the addition of at least 10 characters for the spread, the parentheses and the null expression.

  1. let cond = true;
  2. let obj = {
  3. x: 14,
  4. y: 39,
  5. ...(cond ? {prop1: value1, prop2: value2} : null)
  6. };

Additionally, this behaviour can sometimes be emulated using just the ternary operator with the false expression set to undefined. This workout cannot be used in certain situations however, such as when performing operation an update on a database, as the property is still present in the object. Certain applications may iterate over the keys within an object, using Object.keys or a similar function, and take undesirable action based upon this.

  1. function(cond) {
  2. return {
  3. x: 14,
  4. y: 39,
  5. prop: cond ? true : undefined
  6. };
  7. }