为了账号安全,请及时绑定邮箱和手机立即绑定

比较两个JSON对象,如果键和值使用Javascript匹配,则返回true

比较两个JSON对象,如果键和值使用Javascript匹配,则返回true

元芳怎么了 2021-05-11 21:17:02
我有两个JSON对象,如果键和值匹配,则想返回'true'值。d1和d2的所有三个值都应匹配。var d1 = [{"deviceid":"867874031097770","simno":"232ff33","slot":"1"},{"deviceid":"86787403100","simno":"ss343433","slot":"2"}];var d2 = {"deviceid":"867874031097770","simno":"232ff33","slot":"1"};我尝试使用以下代码,但不适用于JSON值数组。function equals ( x, y ) {    // If both x and y are null or undefined and exactly the same    if ( x === y ) {        return true;    }    // If they are not strictly equal, they both need to be Objects    if ( ! ( x instanceof Object ) || ! ( y instanceof Object ) ) {        return false;    }    // They must have the exact same prototype chain, the closest we can do is    // test the constructor.    if ( x.constructor !== y.constructor ) {        return false;    }    for ( var p in x ) {        // Inherited properties were tested using x.constructor === y.constructor        if ( x.hasOwnProperty( p ) ) {            // Allows comparing x[ p ] and y[ p ] when set to undefined            if ( ! y.hasOwnProperty( p ) ) {                return false;            }            // If they have the same strict value or identity then they are equal            if ( x[ p ] === y[ p ] ) {                continue;            }            // Numbers, Strings, Functions, Booleans must be strictly equal            if ( typeof( x[ p ] ) !== "object" ) {                return false;            }            // Objects and Arrays must be tested recursively            if ( !equals( x[ p ],  y[ p ] ) ) {                return false;            }        }    }    for ( p in y ) {        // allows x[ p ] to be set to undefined        if ( y.hasOwnProperty( p ) && ! x.hasOwnProperty( p ) ) {            return false;        }    }    return true;}
查看完整描述

3 回答

?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

您可以d2对中的每个条目进行分类和比较d1。只需通过提供一个replacer函数作为中的第二个参数来确保在对对象进行字符串化时保持顺序JSON.stringify。


非数组对象的属性不能保证以任何特定顺序进行字符串化。不要依赖于字符串化中同一对象内属性的顺序。


function replacer(obj) {

  return Object.keys(obj).sort();

}


var d1 = [{"deviceid":"867874031097770", "simno":"ss343433", "slot":"1"}, 

          {"deviceid":"867874031097770","simno":"ss343433","slot":"1"}];


var d2 = {"deviceid":"867874031097770","slot":"1", "simno":"ss343433"};


function equals(searchArr, objToCheck) {

  var allEqual = true;

  for (index in searchArr) {

    const item = searchArr[index];

    if (JSON.stringify(item, replacer(item)) !== JSON.stringify(objToCheck, replacer(objToCheck))) {

      (objToCheck)));

      allEqual = false;

      break;

    }

  }

  return allEqual;

}


if (equals(d1, d2)) {

  console.log('All values of properties of d2 match with all entries in d1')

} else {

  console.log('d2 values do not match with all entries in d1');

}


查看完整回答
反对 回复 2021-05-13
  • 3 回答
  • 0 关注
  • 159 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信