首页 > 解决方案 > 以更清洁的方式将属性传递给此

问题描述

是否有另一种干净的方法来编写此代码,以便将数据数组中的属性直接传递给该对象。

        this.Email = data[0].Email;
        this.RealName = data[0].RealName;
        this.JobTitle = data[0].JobTitle;
        this.UserDID = data[0].UserDID;
        this.CreatedDateTime = data[0].CreatedDateTime;
        this.ApplicationCount = data[0].ApplicationCount;
        this.CountApply = data[0].CountApply;
        this.CountResume = data[0].CountResume;
        this.LastEmailAction = data[0].LastEmailAction;
        this.CountEmailActions = data[0].CountEmailActions;
        this.LastResume = data[0].LastResume;
        this.LastApply = data[0].LastApply;

标签: javascriptnode.js

解决方案


如果您希望将所有属性从data[0]分配给 指向的对象this,您可以使用Object.assign()它将所有可枚举属性从源对象复制到目标对象:

Object.assign(this, data[0]);

如果您只想选择属性,那么您可以列出这些属性并遍历它们:

['Email', 'RealName', ...].forEach(prop => {this[prop] = data[0][prop]});

推荐阅读