首页  编辑  

按给定属性列表复制对象属性到另外一个对象 copyProperties

Tags: /Node & JS/   Date Created:
Typescript中,类似Java SpringBoot中的BeanUtils.copyProperties方法:
在两个对象之间,按给定的属性名称数组来复制指定的属性值。
function copyProperties<T extends Object, U extends Object>(src: T, target: U, properties: (keyof T & keyof U)[]): void {
    properties.forEach(prop => {
        if (prop in src) {
            (target as any)[prop] = src[prop];
        }
    });
}

// 示例
interface Source {
    aaa: string;
    bbb: number;
    ccc: boolean;
    ddd: string;
    eee: number;
}

interface Target {
    aaa: string;
    bbb: number;
    ccc: boolean;
    ddd: string;
    fff: string;
}

const src: Source = {
    aaa: 'hello',
    bbb: 123,
    ccc: true,
    ddd: 'world',
    eee: 456
};

const target: Target = {
    aaa: '',
    bbb: 0,
    ccc: false,
    ddd: '',
    fff: 'not copied'
};

copyProperties(src, target, ["aaa", "bbb", "ccc", "ddd"]);

console.log(target);
// 输出: { aaa: 'hello', bbb: 123, ccc: true, ddd: 'world', fff: 'not copied' }