2017-07-22 36 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); 

}