js两个对象合并怎么不覆盖属性?

新手上路,请多包涵

图片描述
我想把 a 和 b 合并,
实际输出的c是这样的
图片描述
期望输出
图片描述
有没有什么办法呢

阅读 12.9k
7 个回答
var a = {
  home: {
    home1: 'home1',
  },
  index: {
    index: 'index1',
  }
}

var b = {
  home: {
    home2: 'home2',
  },
  index: {
    index2: 'index2',
  }
}

function demo (one, two) {
  for(var key in two) {
    for(var k2 in two[key])
    one[key][k2] = two[key][k2]  
  }
  return one
}

console.log(JSON.stringify(demo(a, b))) // => {"home":{"home1":"home1","home2":"home2"},"index":{"index":"index1","index2":"index2"}}

Object.keys(a).forEach(item => { a[item] = {...a[item],...b[item]} })

_.reduce(a, function(result, value, key) {
    result[key] = Object.assign(value,b[key]);
    return result;
}, {});
var a = {
  home: {
    home1: 'home1',
  },
  index: {
    index: 'index1',
  }
}

var b = {
  home: {
    home2: 'home2',
  },
  index: {
    index2: 'index2',
  }
}
var c={};
for (let item in a){
    console.log(a[item])
    if(item in b){
        c[item]=Object.assign(a[item],b[item])
    }
}
console.log(c)

clipboard.png

var obj = Object.keys(a).reduce((obj, item)=>{
    obj[item] = {...a[item], ...b[item]}
    return obj;
}, {});

clipboard.png

推荐问题
宣传栏