How assign 2 different type object(complex objects) attribute by attribute with manually mapping in typescript?(like automapper in C#)

Viewed 32

I have 2 different type of complex object. I want to assign one of them to other by mapping attributes. How can I achieve it?

interface IClassA{
                attribute1: string; //same with IClassB
                attribute2: string; //same with IClassB
                attribute3: number; //different type different mane with IClassB
        };


interface IClassB{
            attribute1: string;
            attribute2: string;
            attr3: string;
    };





var obj1: IClassA= {
             attribute1:  'xxx',
             attribute2:  'yyy',
             attribute3: 5
   };

var obj2: IClassB;


console.log(obj1);

Output is :

[LOG]: {
  "attribute1": "xxx",
  "attribute2": "yyy",
  "attribute3": 5
} 

When I want to make obj2 written, it needs to be like:

"attribute1": "xxx", "attribute2": "yyy", "attr3": "5" }

How can I assign like that obj2 = obj1 .. I need to map attributes by attributes, what is the best way?

I dont want yo use that notation(ASSUME that I have n attribute with same name, just 1 attribute with different name)

obj2.attribute1 = obj1.attribute1; ..... 
1 Answers

You can use a function like this to check each attribute in an object and see if it exists in the second object. If it exists, make the assignment.

interface IClassA{
    attribute1: string; //same with IClassB
    attribute2: string; //same with IClassB
    attribute3: number; //different type different mane with IClassB
};

interface IClassB{
    attribute1: string;
    attribute2: string;
    attr3: string;
};

const automap = (a: any, b: any) => {
    for(const [key, val] of Object.entries(a)) {
        if (b[key] !== undefined) {
            b[key] = val;
        }
    }
}

const obj1: IClassA= {
    attribute1:  'xxx',
    attribute2:  'yyy',
    attribute3: 5
};

let obj2: IClassB = {
    attribute1: 'zzz',
    attribute2: 'www',
    attr3: '42'
};

console.log(obj2);
automap(obj1, obj2);
console.log(obj2);
[LOG]: {
  "attribute1": "zzz",
  "attribute2": "www",
  "attr3": "42"
} 
[LOG]: {
  "attribute1": "xxx",
  "attribute2": "yyy",
  "attr3": "42"
} 
Related