In my scenario, I am dealing with two nested objects named obj1 and obj2. The goal is to compare these objects recursively and then return another object in which each nested key will have a boolean flag indicating equality.
For instance, consider an obj1
like this:
var obj1 = {
prop1: "BAR",
prop2: "foo",
prop3: [
{
id: 1,
prop4: "foo",
prop5: "a"
},
{
id: 2,
prop4: "foo",
prop5: "b"
},
{
id: 3,
prop4: "foo",
prop5: "e"
}
]
}
And an obj2
like this:
var obj2 = {
prop1: "FOO",
prop2: "foo",
prop3: [
{
id: 1,
prop4: "bar",
prop5: "b"
},
{
id: 2,
prop4: "foo",
prop5: "a"
},
{
id: 4,
prop4: "foo",
prop5: "e"
}
],
prop6: "new"
}
The expected output should be:
var equality = {
prop1: false,
prop2: true,
prop3: [
{
id: 1,
prop4: false,
prop5: false
},
{
id: 2,
prop4: true,
prop5: false
},
{
id: 3,
prop4: null,
prop5: null
},
{
id: 4,
prop4: true,
prop5: true
}
],
prop6: true
}
In order to achieve this, I need to compare both objects and return true for matching values. When comparing arrays within the objects, I must use the ID as the key and check if prop4 and prop5 have changed, returning false if they have changed. For data present in obj1 but not in obj2, it should show as null in the result (equality). Data that is only present in obj2 should be flagged as true for all its properties.
I found a solution by Nina Scholz on Stack Overflow, which helped me greatly. The only issue I am facing is regarding the formatting of prop3. I would appreciate it if someone could provide a more suitable solution. As a beginner in JavaScript, learning from this experience would be incredibly valuable.