问题描述
我想深入比较两个json对象(邮递员响应),这些对象包含嵌套对象而不考虑顺序。我需要在邮递员测试中编写此比较。
json1 = {
"a": 1,"b": {
"toto": "toto","array": [
{
"old": {
"value": 1
}
},{
"new": {
"value": 2
}
}
]
}
}
json2 = {
"a": 1,"array": [
{
"new": {
"value": 2
}
},{
"old": {
"value": 1
}
}
]
}
}
json3 = {
"b": {
"toto": "toto",{
"new": {
"value": 2,"other": 4
}
}
]
},"a": 1
}
我希望json1
和json2
显示为相等(仅更改嵌套数组中的顺序)。 json1
和json3
不同。
我见过类似的帖子,但没有找到关于此类对象的答案(如果我错过了,请提前表示抱歉)。
我尝试了几个lodash函数,但是找不到解决方案:
function customizer(baseValue,value) {
if (Array.isArray(baseValue) && Array.isArray(value)) {
return lodash.isEqual(lodash.sortBy(baseValue),lodash.sortBy(value))
}
}
console.log(lodash.isEqualWith(json1,json2,customizer)) -> false,I expect true
console.log(lodash.isEqual((lodash.sortBy(json1),lodash.sortBy(json2)))) -> same as above
console.log(lodash.xor(json1,json2).length) -> 0
console.log(lodash.xor(json1,json3).length) -> 0,I expect different from 0 because of the "other"
我也尝试过isMatch
(和isMatchWith
),但是它太宽容了。我不想让源具有比其他json更多的值(isMatch
仅进行了部分深度比较)
有人可以帮忙吗? 预先谢谢你。
解决方法
我想出了一种对我有用的方法:
function customizer(objValue,srcValue,key,object,source) {
if(Object.keys(object).length !== Object.keys(source).length){
return false;
}
if(typeof objValue ==='object' && typeof srcValue === 'object'){
if(Object.keys(objValue).length !== Object.keys(srcValue).length ){
return false;
}
}
if (Array.isArray(objValue) && Array.isArray(srcValue)) {
if(!(objValue.length === srcValue.length)){
return false;
}
}
}
console.log(lodash.isMatchWith(json1,json2,customizer))