比较两个对象和 return 只有唯一数据

Compare two Objects and return only unique data

我有两个对象,我只想使用下划线 js 提取唯一的数据。

对象 1(默认)

{
   players: "Players: ",
   tableLimit: "Table Limits:",
   newCardBtn: "Add New Card",
   existingCard: "Use existing one",
   contactUs: "Contact Us",
   test: {
      table: 'test'
   }
}

对象 2(覆盖)

  {
    players: "Players: ",
    tableLimit: "Table Limits:",
    newCardBtn: "Add New Card",
    existingCard: "Use existing one",
    test: {
      table: 'test'
    }
  }

最终结果应该是 return 一个包含因覆盖而丢失的数据的列表。在我们的例子中,它应该 return contactUs: "Contact Us"

直到现在我还有这个,但是它 return 没有自定义的默认对象的所有数据:

var def = {
    players: "Players: ",
    tableLimit: "Table Limits:",
    newCardBtn: "Add New Card",
    existingCard: "Use existing one",
    contactUs: "Contact Us",
    test: {
      table: 'test'
   }
}

var custom = {
    players: "Players: ",
    tableLimit: "Table Limits:",
    newCardBtn: "Add New Card",
    existingCard: "Use existing one",
    test: {
      table: 'test'
   }
}

var out = JSON.stringify(Object.assign({}, def, custom));
fs.writeFile("./out.js", out);

这将解析 obj1,如果在 obj2 中没有具有匹配值的匹配 属性,则将其添加到 obj3。您可以在输出中看到结果...

var obj1 = {
  players: "Players: ",
  tableLimit: "Table Limits:",
  newCardBtn: "Add New Card",
  existingCard: "Use existing one",
  contactUs: "Contact Us",
};

var obj2 = {
  players: "Players: ",
  tableLimit: "Table Limits:",
  newCardBtn: "Add New Card",
  existingCard: "Use existing one",
};
  
var obj3 = (function() {
  result = {};
  for (var k in obj1) {
    if (obj2[k] != obj1[k]) {
      result[k] = obj1[k];
    }
  }
  return result;
})();

console.log(obj3);