Javascript / Postman将json与忽略顺序的嵌套对象进行比较

问题描述

我想深入比较两个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
}

我希望json1json2显示为相等(仅更改嵌套数组中的顺序)。 json1json3不同。 我见过类似的帖子,但没有找到关于此类对象的答案(如果我错过了,请提前表示抱歉)。

我尝试了几个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))

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...