简体   繁体   English

在TypeScript中使用解构/扩展来复制具有重命名属性的对象

[英]Using destructuring/spreading to copy object with renamed properties in TypeScript

I need a function that maps object from one type to another: 我需要一个将对象从一种类型映射到另一种类型的函数:

I have an object like this: 我有一个这样的对象:

interface IEntityPerson {
  person_id: number
  name: string
  age: number
  address: IAddress
}

const orig: IEntityPerson = {
  person_id: 1,
  name: 'Ole',
  age: 40,
  address: myAddress
}

I want to use destructuring to map to another type where person_id is renamed to personId: 我想使用解构映射到另一个类型,其中person_id重命名为personId:

interface IRenamed {
  personId: number
  name: string
  age: number
  address: IAddress
}

const newObj: IRenamed = {
  personId: 1,
  name: 'Ole',
  age: 40,
  address: myAddress
}

I tried this but doesn't work: 我尝试了这个,但是不起作用:

export function mapContractTemplate(p: IEntityPerson): IRenamed {
  const renamed = {
    person_id: personId,
    ...rest
  } = p
  return renamed
}

How can I do this? 我怎样才能做到这一点?

Also, notice that the 'address' property is a nested object. 另外,请注意,“ address”属性是一个嵌套对象。 Is there a smart way to do this with destructuring and/or spreading? 是否有一种聪明的方法来进行销毁和/或扩散?

Destructuring an object already defines the destructured properties as fields scoped to that block, they can't be assigned as a group to another field. 解构对象已经将解构的属性定义为范围限定于该块的字段,不能将它们作为组分配给另一个字段。

You can do it like this: 您可以这样做:

export function mapContractTemplate(p: IEntityPerson): IRenamed {
    const { person_id, address, ...rest } = p;
    return {
        personId: person_id,
        address: { ...address },
        ...rest
    }
}

This wil also create a copy of the address field, but it won't create a deep copy of it. 这还将创建地址字段的副本,但不会创建它的深层副本。 So, in case address contains more nested objects or arrays you would have to do the nested destructuring manually. 因此,如果address包含更多的嵌套对象或数组,则必须手动执行嵌套的分解。

Maybe you can simple copy all properties to the a new object and apply the specific differences like this: 也许您可以将所有属性简单地复制到一个新对象,然后应用如下所示的特定区别:

export function mapContractTemplate(p: IEntityPerson): IRenamed {

  // create a new object and add the new property
  const renamed = {
    personId: p.person_id
  };

  // blind copy all properties
  for(var key in p) {
     renamed[key]=p[key];
  }

  // delete the unwanted 'old' property
  delete renamed.person_id;
  return renamed;
}

This code keeps the same instance of address. 此代码保留相同的地址实例。 It wasn't clear to me if you needed cloning of this object as well. 我不清楚您是否还需要克隆该对象。

well there is no dircet way to do it with destructing in my knowlage. 好吧,在我的知识中没有直接的方式来破坏它。 what you can do is 你能做的是

 export function mapContractTemplate(p: IEntityPerson): IRenamed { const clone = JSON.parse(JSON.stringify(p)) // deep clone the object clone.personId = clone.person_id delete clone.person_id; return clone } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM