2017-07-22 24 views
0

使用JavaScript实现两个对象的深度是comapre,如果true不等于等于返回值,则返回false。第一个参数与原始对象相比较,第二个参数用于比较目标对象,该对象属性存在于值中只存在,该属性不存在于原始对象中,如果该对象,则会直接返回false。这里有些例子。两个对象之间的部分深度比较

const object = { 
    id: 1, 
    name: 'test', 
    product: { 
     id: 1, 
     name: 'product' 
    }, 
    updatedAt: 'now' 
}; 
const objectA = { 
    name: 'test', 
    product: { 
     name: 'product' 
    } 
}; 
const objectB = { 
    name: 'test', 
    product: { 
     name: 'anotherProduct' 
    } 
}; 
compare(object, objectA) // return true 
compare(object, objectB) // return false 

回答

0

这里是我提出的解决方案, 小提琴 - https://jsfiddle.net/jayjoshi64/qn70yosx/5/

它具有递归函数,这将检查是否两个给定的对象是对象或隐式对象中的一个。

如果它是对象,它将再次递归检查它们是否相同。 函数比较的代码..

它正在为你的对象工作。

function compare(first,second) 
{ 
    //alert("once"); 
    var flag=true; 

if(typeof second=='object') 
{ 
    //if the variable is of type object 
    if(typeof first!='object') 
    { 
      flag=false 

    } 
    else 
    { 
    //check every key of object 

     $.each(second, function(key, value) { 
      //if socond's key is available in first. 
      if(first.hasOwnProperty(key)) 
      { 
       //recursive call for the value. 
       if(!compare(first[key],second[key])) 
       { 
        flag=false; 
       } 
      } 
      else 
      { 
       flag=false 
      } 
     }); 
     } 
    } 
    else 
    { 
      // if two objects are int,string,float,bool. 
      if(first!=second) 
     { 
       flag=false; 
     } 

    } 
    return(flag); 

}