最近我正在做这个项目。我面临的问题是获取两个JavaScript对象之间的差异。以下是该对象的两个示例。第二个对象有一个额外的键。那么如何获得对象之间的差异。
示例1
{
"title": "JavaScript Tutorial",
"body": "JavaScript",
"comments": [
{
"name": "John Smith",
"comment": "Great article",
"age": 28,
"stars": 4,
"date": "2014-09-01"
},
]
}
示例2
{
"title": "JavaScript tutorial",
"body": "JavaScript.",
"topics":"how learn JavaScript withing 10 days",
"comments": [
{
"name": "John Smith",
"comment": "Great article",
"age": 28,
"stars": 4,
"date": "2014-09-01"
},
]
}
我想要下面这样的结果。以下是两个对象中的关键区别
"主题":"如何在10天内学习JavaScript",
看看deep-diff,你基本上可以像这样使用它来处理你的样本数据
var diff = require('deep-diff').diff;
var lhs = {
"title": "JavaScript Tutorial",
"body": "JavaScript",
"comments": [
{
"name": "John Smith",
"comment": "Great article",
"age": 28,
"stars": 4,
"date": "2014-09-01"
},
]
};
var rhs = {
"title": "JavaScript tutorial",
"body": "JavaScript.",
"topics":"how learn JavaScript withing 10 days",
"comments": [
{
"name": "John Smith",
"comment": "Great article",
"age": 28,
"stars": 4,
"date": "2014-09-01"
},
]
};
var differences = diff(lhs, rhs);
console.log(differences);
将输出
[ DiffEdit {
kind: 'E',
path: [ 'title' ],
lhs: 'JavaScript Tutorial',
rhs: 'JavaScript tutorial' },
DiffEdit {
kind: 'E',
path: [ 'body' ],
lhs: 'JavaScript',
rhs: 'JavaScript.' },
DiffNew {
kind: 'N',
path: [ 'topics' ],
rhs: 'how learn JavaScript withing 10 days' } ]
正如您所看到的,除了新特性之外,还有更多的更改。CCD_ 1性质也表明了这种差异。如果您只需要新属性,那么只需考虑具有kind === 'N'
的对象
如果递归不是一个因素,您可以在两者的属性上循环,检查两者是否都拥有相应的属性。
确保你分别循环两次,这样你就不会得到任何误报。
试试这个代码
function sameKeys (obj1, obj2) {
let diffs = []
for (let prop in obj1) {
if (undefined === typeof obj2[prop]
|| obj2[prop] !== obj1[prop]) {
diffs.push({
type: (obj2[prop] !== undefined ? "Not equal" : "Undefined"),
field: prop,
whichOne: "Object 2",
values: {
object1: obj1[prop],
object2: obj2[prop]
}
})
}
}
for (let prop in obj2) {
if (undefined === typeof obj1[prop]
|| obj1[prop] !== obj2[prop]) {
diffs.push({
type: (obj1[prop] !== undefined ? "Not equal" : "Undefined"),
field: prop,
whichOne: "Object 1",
values: {
object1: obj1[prop],
object2: obj2[prop]
}
})
}
}
return diffs
}