interface type1 {
key1: string;
key2: string;
key3?: type3;
}
interface type2 {
key1: string;
key2: string;
key5: string;
key6: number;
}
interface type3 {
key5?: string;
key6?: number;
}
const obj1: type1 = <type1>{};
const obj2: type2 = {
key1: 'hi',
key2: 'hello',
key5: 'Hola',
key6: 123
};
const obj3: type3 = <type3>{};
const array1: (keyof type2)[] = ['key1', 'key2'];
const array2: (keyof type3)[] = ['key5', 'key6'];
array1.forEach((key: keyof type2) => {
obj1[key] = obj2[key]; /* Error occurred while adding value */
});
array2.forEach((key: keyof type3) => {
obj3[key] = obj2[key]; /* Error occurred while adding value */
});
obj1.key3 = obj3;
console.log(obj1);
I have 3 objects of different types but some keys are common in objects. I want to add values dynamically from one object to another. I've added the code what I tried till now.
Is there any way to achieve it. Practically I've more keys than what I've put on the example. assigning them one by one will be huge and inefficient.
Thanks in advance.
anyI can assign the values directly without error.array1,array2and don't manually define those keys?