0

我试图将一个对象分解为另一个对象,我的意思是从对象 A 到对象 B 的属性子集。我这样做是这样的:

  const User = new UserImpl();
        User.email = user.email;
        User.name = user.name;
        User.family_name = user.familyName;
        User.password = 'Test!';
        User.verify_email = true;
        User.email_verified = false;
        User.blocked = false;
  const {
            email,
            name,
            family_name,
            password,
            verify_email,
            email_verified,
            blocked,
            connection
        } = User;
  const res_user = {
            email,
            name,
            family_name,
            password,
            verify_email,
            email_verified,
            blocked,
            connection
        };
        return res_user;

但是,有没有办法使用 Object.assign() 来做到这一点?或使用箭头 => 函数而不是有两个变量或分两步执行?

谢谢

4

2 回答 2

2

如果您只想复制几个属性,您总是可以摆脱解构并执行以下操作:

  const res_user = {
    email: User.email,
    name: User.name,
    family_name: User.family_name,
    password: User.password,
    verify_email: User.verify_email,
    email_verified: User.email_verified,
    blocked: User.blocked,
    connection: User.connection,
  };
  return res_user;

这段代码比User仅仅为了稍后重构它而解构对象要短。

或者,如果您只想删除几个属性(并且假设您知道没有其他属性),您可以使用rest/spread 参数

const {
   some_prop_i_dont_care_about,
   some_other_prop,
   ...res_user
} = User;
return res_user;

这将创建一个新对象,其中包含上面明确列出的属性之外的所有属性,并将该对象分配给变量res_user

于 2019-06-21T15:46:34.777 回答
2

如果我浅拷贝属性列表,我可能会使用type定义一个pick()函数Pick

const pick = <T, K extends keyof T>(obj: T, ...keys: K[]) =>
  keys.reduce((acc, k) => ((acc[k] = obj[k]), acc), {} as Pick<T, K>);

然后假设你有以下接口和对象

interface User {
  email: string;
  name: string;
  familyName: string;
  password: string;
  verifyEmail: boolean;
  emailVerfified: boolean;
  blocked: boolean;
}

const u: User = {
  email: "luser@example.com",
  name: "Larry",
  familyName: "User",
  password: "th3b1gg3stLUSER",
  verifyEmail: true,
  emailVerfified: false,
  blocked: false
};

console.log(u); // everything

您可以只将您关心的属性复制到一个新对象,如下所示:

const v = pick(u, "name", "familyName", "email");
// const v: Pick<User, "name" | "familyName" | "email">
// const v: {name: string, familyName: string, email: string}

console.log(v); // just name, familyName, email
// {name: "Larry", familyName: "User", email: "luser@example.com"}

希望有帮助;祝你好运!

链接到代码

于 2019-06-21T15:52:05.707 回答