Details. JS compares instances where the values of two Json objects are equal

  • 2020-03-29 23:53:26
  • OfStack


//Compare whether the array is the same
  modeler.compArray=function(array1,array2)
  { 
   if((array1&&typeof array1 ==="object"&&array1.constructor===Array)&&(array2&&typeof array2 ==="object"&&array2.constructor===Array))
   {
      if(array1.length==array2.length)
      {
       for(var i=0;i<array1.length;i++)
       {
        var ggg=modeler.compObj(array1[i],array2[i]);
        if(!ggg)
        {
         return false;
        }

       }

      }
      else
      {
       return false;
      }
   }
   else
   {
    throw new Error("argunment is  error ;");
   }
    return true;
  };
  modeler.compObj=function(obj1,obj2)//To compare two objects for equality, no attribute calculation on the primitive is included
   {
    if((obj1&&typeof obj1==="object")&&((obj2&&typeof obj2==="object")))
    {   
      var count1=modeler.propertyLength(obj1);
      var count2=modeler.propertyLength(obj2);
      if(count1==count2)
      { 
       for(var ob in obj1)
       {
        if(obj1.hasOwnProperty(ob)&&obj2.hasOwnProperty(ob))
        {     

         if(obj1[ob].constructor==Array&&obj2[ob].constructor==Array)//If the property is an array
         { 
          if(!modeler.compArray(obj1[ob],obj2[ob]))
          {
           return false;
          };
         }                  
         else if(typeof obj1[ob]==="string"&&typeof obj2[ob]==="string")//Pure attribute
         {  
         if(obj1[ob]!==obj2[ob])
        {
           return false;
        }
         }
         else if(typeof obj1[ob]==="object"&&typeof obj2[ob]==="object")//Properties are objects
         {  
          if(!modeler.compObj(obj1[ob],obj2[ob]))
        {  
         return false;
        };
         }
         else
         {
        return false;
         }
        } 
        else
        {
         return false;
        }
       }
      }
      else
      {
       return false;
      } 
    }

    return true;
   };
   modeler.propertyLength=function(obj)//Gets the number of properties on an object, not the properties on the object
   {  
    var count=0;
    if(obj&&typeof obj==="object") {
     for(var ooo in obj) {
       if(obj.hasOwnProperty(ooo)) {
         count++;
       }
     }
     return count;
    }else {
     throw new Error("argunment can not be null;");
    }

   };


Test data:

     var data01=[{value:[{id:'asa',value:'dfs'},{}]}];
     var data02=[{value:[{id:'asa',value:'dfs'},{}]}];
     try {
        var jjj=modeler.compArray(data01,data02);
     }catch(e)  {
     }


Related articles: