js对象操作,求解答

{
  a:{ 
     b1: '哈哈哈11111' ,
     b4: '哈哈哈2' ,
  },
  c:{
    c1: 'dadada'
  },
  e: '哈哈哈55555',
  f: '哈哈哈6',
  h: '哈哈哈777'
}


{
  a:{ 
    b1: '哈哈哈',
     b2: '哈哈哈2',
     b3: '哈哈哈3',
  },
  e: '哈哈哈5',
  f: '哈哈哈6',
}

{
  a:{ 
     b1: '哈哈哈11111' ,
     b2: '哈哈哈2' ,
    b3: '哈哈哈3' ,
     b4: '哈哈哈2' ,
  },
  c:{
    c1: 'dadada'
  },
  e: '哈哈哈55555',
  f: '哈哈哈6',
  h: '哈哈哈777'
}

如上,有对象一和对象二,最终想输出对象三,通过js怎么去实现呢?
也就是以对象一为准,对象一和二都有的key,就直接替换成对象一的value,对象一有,对象二没有,就直接加到对象二里面,谢谢各位大佬。菜鸟一个,不知道怎么处理递归

阅读 2.9k
5 个回答
function assiginObj(target = {},sources= {}){
    let obj = target;
    if(typeof target != 'object' || typeof sources != 'object'){
        return sources;
    }
    for(let key in sources){ 
        if(target.hasOwnProperty(key)){
            obj[key] = assiginObj(target[key],sources[key]);
        } else {
            obj[key] = sources[key];
        }
    }
    return obj;
}
let a = {
  a:{ 
    b1: '哈哈哈',
     b2: '哈哈哈2',
     b3: '哈哈哈3',
  },
  e: '哈哈哈5',
  f: '哈哈哈6',
}
let b = {
  a:{ 
     b1: '哈哈哈11111' ,
     b4: '哈哈哈2' ,
  },
  c:{
    c1: 'dadada'
  },
  e: '哈哈哈55555',
  f: '哈哈哈6',
  h: '哈哈哈777'
}
console.log(assiginObj(a,b))
新手上路,请多包涵

这种东西肯定不能帮你写代码,所以只能提示你两点,不会的话就赶紧去学:

1、遍历对象属性
2、递归

let obj1 ={
  a:{ 
     b1: '哈哈哈11111',b4: '哈哈哈2' 
  },
  c:{
    c1: 'dadada'
  },
  e: '哈哈哈55555',
  f: '哈哈哈6',
  h: '哈哈哈777'
}


let obj2 ={
  a:{ 
     b1: '哈哈哈' , b2: '哈哈哈2',  b3: '哈哈哈3'
  },
  e: '哈哈哈5',
  f: '哈哈哈6',
}

let obj3 ={
  a:{ 
    b1: '哈哈哈11111' ,b2: '哈哈哈2', b3: '哈哈哈3', b4: '哈哈哈2'
  },
  c:{
    c1: 'dadada'
  },
  e: '哈哈哈55555',
  f: '哈哈哈6',
  h: '哈哈哈777'
}
const isType = (value, type)=> Object.prototype.toString.call(value) === `[object ${type}]`;
// 将 obj2 合并到 obj1
const deep=(obj1,obj2)=> (Object.entries(obj2).forEach(([key,val])=>obj1[key] = isType(obj1[key],'Object') ? deep(obj1[key],obj2[key]) : val),obj1)
deep(obj2,obj1);

image.png

function getAssign(obj) {

return [...new Set(`${Array.from(arguments).map(item => Object.keys(item))}`.split(','))].reduce((total, item) => ({
    ...total, [item]: Array.from(arguments).reduce((t, j) => { if (typeof j[item] === 'object') { return { ...getAssign(j[item]), ...t} } else { return Array.from(arguments)[0][item] } },{})
}), {})

}

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题