源码
将两对象的属性合并,深层对象也可以
function isDef(value: any): boolean {
// value:any 表示传入的参数是任意类型 boolean 表示返回值是boolean类型
return value !== undefined && value !== null;
// 传入的值不能是undefined 也不能是null
}
// in 15.686s 0.486s
function isObj(x: any): boolean {
debugger
//判断一个值是否是 对象类型
// 传入的参数 是 any 任意类型i
// 返回值是 boolean
const type = typeof x;
// typeof 判断数据类型
// typeof 判断数据类型时 null 也是 object 所以 type 不能为null
// 函数也是 对象
return x !== null && (type === 'object' || type === 'function');
}
const { hasOwnProperty } = Object.prototype;
//判断对象是否包含某个属性(不包含对象原型上的属性)
type objectType = {
[key: string]: any;
}
function assignKey(to: objectType, from: objectType, key: string) {
const val = from[key];
// 拿到老的数据的 某个key的值
if (!isDef(val)) {// 当前key对应的 老数据的值 是undefined就return
return;
}
if (!hasOwnProperty.call(to, key) || !isObj(val)) {
// 如果目标对象的 这个key 不存在就 老数据对应的key值 赋值给 目标对象to
to[key] = val;
} else {
to[key] = deepAssign(Object(to[key]), from[key]);
}
}
function deepAssign(to: objectType, from: objectType) {
Object.keys(from).forEach(key => {
assignKey(to, from, key);
});
return to;
}
测试
let toInfo={
name:"123",
age:'16',
more:{
hobby:'打篮球',
address:'合肥'
},
color:'red'
}
let fromInfo={
name:"12343553",
age:'16545353',
more:{
hobby:'打篮球5353',
address:'合肥5353'
},
sex:'男'
}
let result: objectType = deepAssign(toInfo,fromInfo)
console.log("result",result)
深拷贝
import { deepAssign } from './deep-assign';
export function deepClone(obj: object): object {
if (Array.isArray(obj)) {
return obj.map(item => deepClone(item));
}
if (typeof obj === 'object') {
return deepAssign({}, obj);
}
return obj;
}