比较两个对象,并返回唯一的数据
我有两个对象,我只想提取使用下划线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);
回答:
这将解析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);
以上是 比较两个对象,并返回唯一的数据 的全部内容, 来源链接: utcz.com/qa/261894.html