检查Object1的键是否在Object2中是否比较值

时间:2018-07-20 15:11:24

标签: javascript arrays object

我将如何执行以下操作。我需要查看我的object1.keys是否在object2中,如果键在那里,我需要比较该值,如果值不同,则需要用Object1的值替换Object2的值。

对象1:

object1 = {
   firstName: "Bob",
   lastName: "Smith",
   dob: "May 25, 1977"
}

Object2:

object2 = {
   firstName: "Bobby",
   lastName: "Jones",
   dob: "May 25, 1977",
   created: "May 24, 1977",
   userLevel: "jedi"
}

Object2的所需输出:

object2 = {
   firstName: "Bob",
   lastName: "Smith",
   dob: "May 25, 1977",
   created: "May 24, 1977",
   userLevel: "jedi"
}

2 个答案:

答案 0 :(得分:1)

 Object.assign(object2, object1);

或不突变object2而是创建一个新对象:

 const newObj = {...object2, ...object1}

这将所有值从object1分配给object2。如果它们相同,则我们复制它们都没关系。

答案 1 :(得分:1)

只需在第一个对象上使用in并进行比较

let object1 = {
   firstName: "Bob",
   lastName: "Smith",
   dob: "May 25, 1977"
}

let object2 = {
   firstName: "Bobby",
   lastName: "Jones",
   dob: "May 25, 1977",
   created: "May 24, 1977",
   userLevel: "jedi"
}

for(let key in object1){
  if(object2[key]){
    object2[key] = object1[key]
  }
}

console.log(object2);