当前位置:网站首页>Deep merge object deep copy of vant source code parsing

Deep merge object deep copy of vant source code parsing

2022-07-05 20:58:00 The legend of Feng

Source code

Merge the properties of two objects , Deep objects can also

function isDef(value: any): boolean {
    // value:any  Indicates that the parameter passed in is of any type   boolean  Indicates that the return value is boolean type 
    return value !== undefined && value !== null;
    //  The value passed in cannot be undefined  Nor is null
}
//  in 15.686s  0.486s

function isObj(x: any): boolean {
    debugger
    // Judge whether a value is   object type 
    //  Incoming parameter   yes  any  Any type i
    //  The return value is  boolean
    const type = typeof x;
    // typeof  Judge data type 
    // typeof  When judging the data type  null  It's also  object  therefore  type  Not for null
    //  The function is also   object 
    return x !== null && (type === 'object' || type === 'function');
}
const { hasOwnProperty } = Object.prototype;
// Determine whether an object contains an attribute ( Does not include attributes on the object prototype )
type objectType = {
    [key: string]: any;
}
function assignKey(to: objectType, from: objectType, key: string) {
    const val = from[key];
    //  Get the old data   Some key Value 

    if (!isDef(val)) {//  At present key Corresponding   Value of old data   yes undefined Just return
        return;
    }

    if (!hasOwnProperty.call(to, key) || !isObj(val)) {
        //  If the target object's   This key  If it doesn't exist   The old data corresponds to key value   Assign a value to   Target audience 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;
}

test

let toInfo={
    name:"123",
    age:'16',
    more:{
        hobby:' To play basketball ',
        address:' Hefei '
    },
    color:'red'
}
let fromInfo={
    name:"12343553",
    age:'16545353',
    more:{
        hobby:' To play basketball 5353',
        address:' Hefei 5353'
    },
    sex:' male '
}
let result: objectType = deepAssign(toInfo,fromInfo)
console.log("result",result)

Deep copy

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;
}

原网站

版权声明
本文为[The legend of Feng]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207052057407912.html