This answer describes a solution for the problem using the DeltaJSON REST API. DeltaJSON is a commercial product that provides the API either as a service (SaaS) or via a REST server that can be run locally:
- Start the DeltaJSON Rest Server (requires Java installation and a license file):
java -jar deltajson-rest-1.1.0.jar
- In your JavaScript, call the DeltaJSON REST API with the
arrayAlignment
property set to orderless
.
The sample code below shows how to invoke the API with this property setting:
async function runTest() {
const group1 = {
id: 123,
users: [
{ id: 234, name: "John" },
{ id: 345, name: "Mike" }
]
};
const group2 = {
id: 123,
users: [
{ id: 345, name: "Mikey" },
{ id: 234, name: "John" }
]
};
// call wrapper function that makes the REST API call:
const isEqual = await compare(group1, group2);
// log the comparison result: true
console.log("isEqual", isEqual);
}
async function compare(aData, bData) {
const aString = JSON.stringify(aData);
const bString = JSON.stringify(bData);
const blobOptions = { type: "application/json" };
var formdata = new FormData();
formdata.append("a", new Blob([aString], blobOptions));
formdata.append("b", new Blob([bString], blobOptions));
formdata.append("arrayAlignment", "orderless");
const myHeaders = new Headers();
myHeaders.append("Accept", "application/json");
var requestOptions = {
method: "POST",
headers: myHeaders,
body: formdata,
redirect: "follow"
};
try {
const response = await fetch(
"http://localhost:8080/api/json/v1/compare",
requestOptions
);
const jsonObj = await response.json();
console.log(jsonObj);
const dataSets = jsonObj.dx_deltaJSON.dx_data_sets;
const isEqual = dataSets === "A=B";
return isEqual;
} catch (e) {
console.error(e);
}
}
// run the test:
runTest(); // true
Explanation:
The DeltaJSON Rest API response is an annotated form of the JSON inputs. Extra dx_
prefixed properties are added to describe the changes. A metadata dx_deltaJSON
property is also included in the JSON.
The value of the dx_deltaJSON
property is an object that has a dx_data_sets
property that we can test to see (in a two-way comparison) that the value is A=B
.
Here is the result where there are slightly different inputs to that in the question. Here, as well as the order of the array items being changed, 'Mike' has been changed to 'Mikey':
{
"dx_deltaJSON": {
"dx_data_sets": "A!=B",
"dx_deltaJSON_type": "diff",
"dx_deltaJSON_metadata": {
"operation": {
"type": "compare",
"input-format": "multi_part",
"output-format": "JSON"
},
"parameters": {
"dxConfig": [],
"arrayAlignment": "orderless",
"wordByWord": false
}
},
"dx_deltaJSON_delta": {
"id": 123,
"users": [
{
"id": 345,
"name": {
"dx_delta": {
"A": "Mike",
"B": "Mikey"
}
}
},
{
"id": 234,
"name": "John"
}
]
}
}
}