从属性对象创建对象的更好方法?

时间:2018-07-11 13:26:12

标签: javascript es6-class destructuring spread-syntax

在我的应用中,我正在使用API​​请求中的数据创建几个不同的对象,如下所示:

const newRelationship = new Relationship(
    data.id,
    data.account_id,
    data.name,
    data.description,
    data.created_at,
    data.created_by,
    data.deleted_at,
    data.deleted_by,
    data.updated_at,
    data.updated_by,
);

这感觉有点麻烦。有没有更好的方法(一行)来执行此操作,而不是像这样手动写出所有参数?

我希望能得到以下类似的信息,但我还没有100%进行价差/结构调整。

const newRelationship = new Relationship(...data);

我的关系构造函数如下:

constructor(id, accountId, name, description, createdAt, createdBy, updatedAt, updatedBy, deletedAt, deletedBy) {
    this.id = id || '';
    this.accountId = accountId || '';
    this.name = name || '';
    this.description = description || '';
    this.createdAt = createdAt || '';
    this.createdBy = createdBy || '';
    this.deletedAt = deletedAt || '';
    this.deletedBy = deletedBy || '';
    this.updatedAt = updatedAt || '';
    this.updatedBy = updatedBy || '';
}

2 个答案:

答案 0 :(得分:3)

将您的构造函数简化为:

const defaults = { id: "", name: "", /*...*/ };

//...

constructor(options) {
 Object.assign(this, defaults, options);
}

然后您可以做:

new Relationship(data)

答案 1 :(得分:0)

如果您要编写类/函数( opinion ),我将在参数中进行对象分解,这表明您将对象传递给函数并枚举了属性(可以如果您希望在destruct语句中将其重命名)。如果您使用的代码最终无法更新,建议您将数组扩展与Object.values()

一起使用

class Relationship {
  constructor({ id, account_id, name, description, created_at, created_by, deleted_at, deleted_by, updated_at, updated_by }) {
    // do stuff with your variables
    console.log(`ID is ${id}`);
  }
}

class OtherRelationship {
  constructor(id, account_id, name, description, created_at, created_by, deleted_at, deleted_by, updated_at, updated_by) {
    // do stuff with your variables
    console.log(`ID is ${id}`);
  }
}

const dummyParams = { 
  id: 1, 
  account_id: 1, 
  name: 'test', 
  description: 'tesssst', 
  created_at: 'some date', 
  created_by: 1, 
  deleted_at: 'some date', 
  deleted_by: 1, 
  updated_at: 'some date', 
  updated_by: 1, 
}

const newRelationship = new Relationship(dummyParams);
const newOtherRelationship = new OtherRelationship(...Object.values(dummyParams))