销毁TypeScript对象

时间:2019-06-21 15:35:48

标签: typescript object-destructuring

我正在尝试将一个对象分解为另一个对象,我的意思是将属性的子集从对象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()呢?还是使用arrow =>函数而不是拥有两个变量或分两步进行?

谢谢

2 个答案:

答案 0 :(得分: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 parameter

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

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

答案 1 :(得分:2)

如果我是浅表复制属性列表,则可能会定义a pick() function using the Pick type

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"}

希望有所帮助;祝你好运!

Link to code