var a = [{
id: 'Monday',
slots: [{
end: "05:00:00 PM",
start: "08:00:00 AM"
},
{
end: "04:00:00 PM",
start: "03:00:00 AM"
}
]
},
{
id: 'Tuesday',
slots: [{
end: "05:00:00 PM",
start: "08:00:00 AM"
}]
}
];
var b = [{
id: 'Monday',
slots: [{
end: "04:00:00 PM",
start: "06:00:00 AM"
},
{
end: "03:00:00 PM",
start: "02:00:00 AM"
}
]
},
{
id: 'Tuesday',
slots: [{
end: "05:00:00 PM",
start: "08:00:00 AM"
}]
},
{
id: 'Wednesday',
slots: [{
end: "05:00:00 PM",
start: "08:00:00 AM"
}]
}
];
I tried JSON.stringify(a) === JSON.stringify(b) but as it is nested objects it is not working out. Is there any way to compare both array of nested objects upto start and end?
id(key)s will be same way in both a and b, only timeslots and it's values will change
Here you can check the value of each and evry nested array's object value .
Below code will console that both the array's are same
If you change any value of object , it will result into Both the array's are not same
var a = [{
id: 'Monday',
slots: [{
end: "05:00:00 PM",
start: "08:00:00 AM"
},
{
end: "04:00:00 PM",
start: "03:00:00 AM"
}
]
},
{
id: 'Tuesday',
slots: [{
end: "05:00:00 PM",
start: "08:00:00 AM"
}]
}
];
var b = [{
id: 'Monday',
slots: [{
end: "05:00:00 PM",
start: "08:00:00 AM"
},
{
end: "04:00:00 PM",
start: "03:00:00 AM"
}
]
},
{
id: 'Tuesday',
slots: [{
end: "05:00:00 PM",
start: "08:00:00 AM"
}]
}
];
var flag = false;
if (a.length != b.length) {
flag = true;
console.log("Both array are not same as there don't have equal length");
}
if (flag == false) {
a.forEach(function(aObject) {
b.forEach(function(bObject) {
if (aObject.id == bObject.id) {
for (var i = 0; i < aObject.slots.length; i++) {
if ((aObject.slots[i].end != bObject.slots[i].end) || (aObject.slots[i].start != bObject.slots[i].start)) {
flag = true;
console.log("Both arrays are not equal");
}
}
}
});
});
}
if(flag == true){
console.log("both arrays are not same");
}
else{
console.log("both arrays are same ");
}
You can checkout the result of my running code .