向对象添加新项,并且不更新js中对象的现有键

时间:2018-08-26 04:00:09

标签: javascript jquery

我有2个对象,我想创建一个函数,在该函数中我可以传递两个对象,并且该函数应该是一个新对象,该对象将添加在第二个对象中找到的新项目,但不应更新第一个对象上的现有键

例如:-

var a  = {
   name:'luisa kate should remain same',
   cast:'THis will remain as it is.'
}

var b = {
  name:'luisa kate should be not updated object because there is already name in object a ',
  school:'lords light academy should be added in new object'
}

 function update(a, b) {
   var c = {};
   for (var key in a) {
     c[key] = a[key];
   }
   for (var key in b){
     if(key in b){

     }else{
       c[key] = (Array.isArray(a[key])) ? a[key].concat(b[key]) : b[key];  
     }
   } 
   return c
 }
 console.log(update(a,b))

预期输出:-

{
   name:'luisa kate should remain same',
   cast:'THis will remain as it is.'
   school:'lords light academy should be added in new object'
}

我在上述更新功能中发挥了很多作用,但是我无法解决,请帮助我。

2 个答案:

答案 0 :(得分:0)

我认为您可以使用对象分配

var a  = {
   name:'luisa kate should remain same',
   cast:'THis will remain as it is.'
}

var b = {
  name:'luisa kate should be not updated object because there is already name in object a ',
  school:'lords light academy should be added in new object'
}

c = Object.assign(b, a);
console.log(c);

答案 1 :(得分:0)

您也可以尝试以下方法:

var a = { name:'luisa kate should remain same', cast:'THis will remain as it is.' }
var b = { name:'luisa kate should be not updated object because there is already name in object a ', school:'lords light academy should be added in new object' };
var c={}, k;
[a,b].forEach(function(O){
    for(k in O) if(typeof(c[k])=="undefined") c[k]=O[k];
});

console.log(JSON.stringify(c));

此外,如果您需要两个值(类似于您自己的解决方案):

var c={}, k;
[a,b].forEach(function(O){
    for(k in O) if(typeof(c[k])=="undefined") c[k]=O[k]; else c[k]=[c[k],O[k]];
});