首页 工具 正文
  • 本文约560字,阅读需3分钟
  • 59
  • 0

js合并对象

摘要

js深度递归合并两个对象

const mergeObject=function (oldObj, newObj) {
    for (let key in newObj) {
        if (newObj.hasOwnProperty(key)) {
            if (oldObj[key] === undefined) {
                oldObj[key] = newObj[key];
            } else if ( typeof newObj[key] !== "object" ||newObj[key] === null ||newObj[key] instanceof Function ) {
                oldObj[key] = newObj[key];
            } else {
                mergeObject(oldObj[key], newObj[key]);
            }
        }
    }
    return oldObj;
}
let obj1={obj1:{obj1_1:{},fn:()=>{},str:"str1",num:11,arr:[1,2,3]}}
let obj2={obj1:{obj1_1:{},fn1:()=>{},str:"str2",num:11,arr:[4,5,6]}}
console.log(mergeObject(obj1,obj2))
/*
输出
{
  obj1: {
    obj1_1: {},
    str:"str1",
    fn:()=>{},
    fn1:()=>{},
    num: 11,
    arr: [ 4, 5,6 ]
  }
}
*/
评论
友情链接