一、ES6 简洁赋值法
利用 ES6 属性简写和动态键名特性快速匹配键值:
// 接口返回数据
const responseData = { id: 1, name: 'John', age: 25 };
// 自定义对象
const myObj = { id: null, name: null };
// 动态赋值匹配键
const assignMatchedKeys = (target, source) => {
Object.keys(target).forEach(key => {
if (source.hasOwnProperty(key)) {
target[key] = source[key];
}
});
return target;
};
assignMatchedKeys(myObj, responseData);
// 结果: { id: 1, name: 'John' }
二、手动遍历比对法
通过双重循环仅赋值键名相同的属性
function safeAssign(target, source) {
for (const key of Object.keys(target)) {
if (key in source) {
target[key] = source[key];
}
}
return target;
}
三、TypeScript 类型安全方案
利用泛型约束和 keyof
确保键值类型匹配:
interface ResponseType {
id: number;
name: string;
extra?: string;
}
interface MyObject {
id: number;
name: string;
}
const assignWithType = <T extends MyObject>(target: T, source: ResponseType): T => {
(Object.keys(target) as Array<keyof T>).forEach(key => {
if (source.hasOwnProperty(key)) {
target[key] = source[key as keyof ResponseType];
}
});
return target;
};
四、注意事项
- 键名严格匹配:需注意大小写和特殊字符差异
- 类型兼容性:即使键名相同,值类型不一致时需做类型转换
- 深拷贝需求:若对象含嵌套结构,建议使用深拷贝工具(如
lodash.cloneDeep
)