比较两个对象并仅返回唯一数据

时间:2017-03-08 09:20:05

标签: javascript underscore.js

我有两个对象,我想只使用下划线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'
    }
  }

最终结果应该返回一个列表,其中包含覆盖中缺少的数据。在我们的例子中,它应该返回contactUs: "Contact Us"

直到现在我有了这个,但它返回默认对象中没有自定义的所有数据:

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);

1 个答案:

答案 0 :(得分:2)

这将解析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);