【问题标题】:Javascript object declaration with ternary operator带有三元运算符的 Javascript 对象声明
【发布时间】:2021-12-07 10:44:39
【问题描述】:

我在我的一个组件中声明一个对象,如下所示:

const data = {
        user: id,
        userRole: role,
        teacherdepartment: department
}

但现在我想动态地做这个声明取决于一个特定的值,如下所示:

let usertype='teacher';
const data = {
        user: id,
        userRole: role,
        if(usertype=='teacher'?(teacherdepartment:tdepartment):(studentDepartment:sdepartment))
}

这可能吗。我知道我可以用嵌套的三元运算符来做到这一点。但是在对象结构内部有什么简单的行可以做到这一点吗?

更新:可以在对象声明中使用三元轻松设置对象值,但这是针对对象键的,因此这不是 this 的重复项。另外,在上面的例子中,我放了一个简单的对象。如果对象内部有一些子条件和三元条件,则为图像。

【问题讨论】:

标签: javascript conditional-operator


【解决方案1】:

我认为这可以重构为

let usertype = 'teacher';

let departmentProperty = usertype === 'teacher' ? 'teacherdepartment' : 'studentDepartment';
let departmentValue = usertype === 'teacher' ? 'teacherdepartmentValue' : 'studentDepartment';
const data = {
    user: 'id',
    userRole: 'role',
    [departmentProperty]: departmentValue,
};

console.log(data)

【讨论】:

    【解决方案2】:

    尝试对键和值都使用条件运算符。通过在键表达式周围添加[] 可以使键动态化。

    伪代码

    const data = {
        user: id,
        userRole: role,
        [usertype=='teacher'? 'teacherdepartment' : 'studentDepartment']: usertype=='teacher'? tdepartment: sdepartment,
    }
    

    工作代码

    const usertype = 'student';
    const tdepartment = 'tdepartment';
    const sdepartment = 'sdepartment';
    const id = 'id';
    const role = 'role';
    const data = {
      user: id,
      userRole: role,
      [usertype=='teacher'? 'teacherdepartment' : 'studentDepartment']: usertype=='teacher'? tdepartment: sdepartment,
    };
    console.log(data)

    【讨论】:

      【解决方案3】:

      我会完全避免使用三元运算符,因为它们在很多情况下都难以阅读。相反,我会创建一个将用户类型映射到字符串值的字典,然后使用该信息动态创建属性。

      const userType = 'teacher';
      
      const dict = { teacher: 'tdepartment', student: 'sdepartment' };
      
      const data = {
        user: 'id',
        userRole: 'role',
        [`${userType}Department`]: dict[userType]
      }
      
      console.log(data);

      【讨论】:

        【解决方案4】:

        虽然此可以在“单线”IMO 中完成以保持可读性,但不应该。

        相反,检查usertype 并创建一个对象以包含在生成的data 对象中。这样,基于usertype 的更改是孤立的并且易于推理。它还允许基于usertype 进行其他更改,因为它与静态属性隔离。

        const deptInfo = usertype === 'teacher' ? { teacherDepartment: tDepartment }
          : { studentDepartment: sDepartment }
        
        const data = {
          ...deptInfo,
          user: id,
          userRole: role,
        }
        

        【讨论】:

          猜你喜欢
          • 2015-01-22
          • 1970-01-01
          • 1970-01-01
          • 2020-05-21
          • 2019-07-21
          • 1970-01-01
          • 1970-01-01
          • 2023-02-03
          相关资源
          最近更新 更多