简体   繁体   English

Javascript / Typescript映射较大对象的源对象属性

[英]Javascript/Typescript map a source object properties from a larger object

I have a target class like this: 我有一个这样的目标类:

export interface person{
      name: string;
      age: string;
    //and another 40 properties
    }

I have a larger source object like: 我有一个更大的源对象,如:

 export interface BigPerson{
      name: string;
      age: string;
    //and another 100 properties
    }

My target have all the source properties but one (salary). 我的目标具有所有源属性,但只有一个(工资)。

How can i get map the source data to target using javascript deconstruction or spread operator? 如何使用javascript解构或散布运算符将源数据映射到目标?

can i try something like 我可以尝试类似的东西吗

let {personObj: person} = bigPersonObj

if I use the common properties then I have to write a 30 line code 如果我使用通用属性,那么我必须编写30行代码

let {name,age,race,all my 30 properties} : ...bigPersonObj

Is there any shortcuts using spread or deconstruction? 是否有使用传播或解构的快捷方式?

This sounds like a JavaScript problem. 这听起来像JavaScript问题。

Since interfaces are just types, then you can't use them at runtime. 由于接口只是类型,因此您不能在运行时使用它们。

So you need to create a concrete object to pick from the big person, however this cannot be done with deconstruction or spread, my best answer would be to create an array of properties and reduce them to an object. 因此,您需要创建一个要从大人物那里挑选的具体对象,但是这不能通过解构或传播来完成,我最好的答案是创建一个属性数组并将它们简化为一个对象。

const reduceToPerson = (sum, element) => {
    sum[element] = bigPersonObj[element];
    return sum;
});
const person = ["name", "age", ...].reduce(reduceToPerson, {});

You could also do the 30 properties the way you want it 您也可以按照自己的方式来做30个属性

const {name, age, ...}: person = bigPersonObject;

However you can't really reuse this code compared to an array. 但是,与数组相比,您无法真正重用此代码。

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

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