JS对象深度合并封装方法源码。

2023-12-18 17:36:34

导入的方法看上一篇文章。

import deepClone from "./deepClone";

// JS对象深度合并
function deepMerge(target = {}, source = {}) {
?? ?target = deepClone(target);
?? ?if (typeof target !== 'object' || typeof source !== 'object') return false;
?? ?for (var prop in source) {
?? ??? ?if (!source.hasOwnProperty(prop)) continue;
?? ??? ?if (prop in target) {
?? ??? ??? ?if (typeof target[prop] !== 'object') {
?? ??? ??? ??? ?target[prop] = source[prop];
?? ??? ??? ?} else {
?? ??? ??? ??? ?if (typeof source[prop] !== 'object') {
?? ??? ??? ??? ??? ?target[prop] = source[prop];
?? ??? ??? ??? ?} else {
?? ??? ??? ??? ??? ?if (target[prop].concat && source[prop].concat) {
?? ??? ??? ??? ??? ??? ?target[prop] = target[prop].concat(source[prop]);
?? ??? ??? ??? ??? ?} else {
?? ??? ??? ??? ??? ??? ?target[prop] = deepMerge(target[prop], source[prop]);
?? ??? ??? ??? ??? ?}
?? ??? ??? ??? ?}
?? ??? ??? ?}
?? ??? ?} else {
?? ??? ??? ?target[prop] = source[prop];
?? ??? ?}
?? ?}
?? ?return target;
}

文章来源:https://blog.csdn.net/2301_77742545/article/details/135057515
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。