ES6/ES7中“可选"对象键的简洁/简洁语法? [英] Succinct/concise syntax for 'optional' object keys in ES6/ES7?

查看:90
本文介绍了ES6/ES7中“可选"对象键的简洁/简洁语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ES6/ES7中已经有很多酷功能用于定义Javascript对象.但是,以下模式在Javascript中很常见:

There are already a lot of cool features in ES6/ES7 for defining Javascript objects. However, the following pattern is common in Javascript:

const obj = { 
  requiredKey1: ..., 
  requiredKey2: ... 
};

if (someCondition) { 
  obj.optionalKey1 = ...;
}

有没有一种方法可以同时使用可选键和必需键来定义对象?

Is there a way to define the object all at once with both optional and required keys?

推荐答案

您可以使用对象传播以具有可选属性.

You can use object spread to have an optional property.

注意:对象保留/扩展是ECMAScript的第4阶段建议.您可能需要 babel转换才能使用它.

Note: Object Rest/Spread is a stage 4 proposal for ECMAScript. You might need the babel transform to use it.

let flag1 = true;
let flag2 = false;

const obj = { 
  requiredKey1: 1, 
  requiredKey2: 2,
  ...(flag1 && { optionalKey1: 5 }),
  ...(flag2 && { optionalKey2: 6, optionalKey3: 7 }),
  ...(flag1 && { optionalKey4: 8, optionalKey5: 9 })
};

console.log(obj);

这篇关于ES6/ES7中“可选"对象键的简洁/简洁语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆