function compareObjects(obj1, obj2, keysToCompare) {
return keysToCompare.every(x => obj1[x] instanceof Array ?
obj1[x].every((y, yi) => compareObjects(y, obj2[x][yi], Object.keys(y))) :
obj1[x] == obj2[x]);
}
// Nothing is different - should work
console.log(compareObjects({
name: 'John',
surname: 'doe',
reference: [{
name: 'jane',
surname: 'smith',
},
{
name: 'kate',
surname: 'post'
},
],
id: '12364',
weight: '50',
Oid: '456978',
code: '12',
}, {
name: 'John',
surname: 'doe',
reference: [{
name: 'jane',
surname: 'smith',
}, {
name: 'kate',
surname: 'post',
}],
id: '4589632',
weight: 50,
policy: '745896',
result: 'test',
documents: 'no',
launch: 'no',
}, [
'name',
'surname',
'reference',
'weight',
]));
// One key is different - should fail
console.log(compareObjects({
name: 'John',
surname: 'doe',
reference: [{
name: 'jane',
surname: 'smith',
}, {
name: 'kate',
surname: 'post',
}],
id: '12364',
weight: '50',
Oid: '456978',
code: '12',
}, {
name: 'John',
// This value is different
surname: 'FOOL',
reference: [{
name: 'jane',
surname: 'smith',
}, {
name: 'kate',
surname: 'post',
}],
id: '4589632',
weight: 50,
policy: '745896',
result: 'test',
documents: 'no',
launch: 'no',
}, [
'name',
'surname',
'reference',
'weight',
]));
// One key is different - should fail
console.log(compareObjects({
name: 'John',
surname: 'doe',
reference: [{
name: 'jane',
surname: 'smith',
}, {
name: 'kate',
surname: 'post',
}],
id: '12364',
weight: '50',
Oid: '456978',
code: '12',
}, {
name: 'John',
surname: 'doe',
reference: [{
name: 'jane',
// This value is different
surname: 'FOOL',
}, {
name: 'kate',
surname: 'post',
}],
id: '4589632',
weight: 50,
policy: '745896',
result: 'test',
documents: 'no',
launch: 'no',
}, [
'name',
'surname',
'reference',
'weight',
]));
// Position is different - should work
console.log(compareObjects({
name: 'John',
surname: 'doe',
reference: [{
name: 'jane',
surname: 'smith',
position: 10,
},
{
name: 'kate',
surname: 'post',
position: 10,
},
],
id: '12364',
weight: '50',
Oid: '456978',
code: '12',
}, {
name: 'John',
surname: 'doe',
reference: [{
name: 'jane',
surname: 'smith',
position: 10,
}, {
name: 'kate',
surname: 'post',
position: 15,
}],
id: '4589632',
weight: 50,
policy: '745896',
result: 'test',
documents: 'no',
launch: 'no',
}, [
'name',
'surname',
'reference',
'weight',
]));
// Everything is same - should work (including position)
console.log(compareObjects({
name: 'John',
surname: 'doe',
reference: [{
name: 'jane',
surname: 'smith',
position: 10,
},
{
name: 'kate',
surname: 'post',
position: 10,
},
],
id: '12364',
weight: '50',
Oid: '456978',
code: '12',
}, {
name: 'John',
surname: 'doe',
reference: [{
name: 'jane',
surname: 'smith',
position: 10,
}, {
name: 'kate',
surname: 'post',
position: 10,
}],
id: '4589632',
weight: 50,
policy: '745896',
result: 'test',
documents: 'no',
launch: 'no',
}, [
'name',
'surname',
'reference',
'weight',
]));