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"
}]
}
];
我尝试了JSON.stringify(a)=== JSON.stringify(b),但是由于它是嵌套对象,因此无法正常工作。有什么方法可以比较两个嵌套对象的数组,直到开始和结束?
id(key)在a和b中的用法都相同,只有时隙及其值会改变
答案 0 :(得分:0)
使用lodash中的_.differenceWith
,并传递一个比较器,该比较器比较两个数组,如下所示:
_.differenceWith(a, b, _.isEqual);
OR
a.sort().every((value, index) => value === b.sort()[index])
答案 1 :(得分:0)
在这里,您可以检查每个的值并估算嵌套数组的对象值。
下面的代码将证明两个数组都是相同的
如果更改object的任何值,将导致两个数组都不相同
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 ");
}
您可以签出我正在运行的代码的结果。