简体   繁体   中英

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?

can i try something like

let {personObj: person} = bigPersonObj

if I use the common properties then I have to write a 30 line code

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

Is there any shortcuts using spread or deconstruction?

This sounds like a JavaScript problem.

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

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

However you can't really reuse this code compared to an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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