2016-12-14 139 views
0

可以說有兩個對象,但一個對象的屬性與另一個不同。有沒有辦法找出哪些屬性匹配?如何檢查兩個對象屬性是否匹配?

例如

var objectOne = { 
    boy: "jack", 
    girl: "jill" 
} 


var objectTwo = { 
    boy: "john", 
    girl: "mary", 
    dog: "mo" 
} 

編輯:應該告訴我boygirl屬性名在兩個對象中找到。

+0

您的例子沒有表現出很大的。你什麼意思? – Li357

+1

所以你想要一個屬性*名稱*在兩個對象中的列表,而不考慮它們的*值*是什麼?我們應該假設沒有物體嵌套? – nnnnnn

+0

@ nnnnnn。對,就是這樣。 – Deke

回答

2
var in_both = []; 
for (var key in objectOne) { // simply iterate over the keys in the first object 
    if (Object.hasOwnProperty.call(objectTwo, key)) { // and check if the key is in the other object, too 
     in_both.push(key); 
    } 
} 

C.f.現在https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

,如果你想測試,如果值是相同的,也不止代碼內if的條件/身體根本補充。

+0

爲什麼不'objectTwo.hasOwnProperty(key)'? '.call()'如何提供幫助? (有趣的選擇鏈接到*德文文檔。) – nnnnnn

+0

@nnnnnn,'objectTwo'可以有自己的項目'hasOwnProperty'。不使用'.call'是一個簡單的攻擊媒介,儘管它不會造成比DOS更多的攻擊。糟糕,沒有注意到我連接了錯誤的語言。您可以簡單地在下次編輯問題。 – kay

+0

夠公平的。我想在我自己的代碼中,我通常處理自己創建的對象,那裏肯定不會有自己的'hasOwnProperty'。但是你的方式適用於任何對象。 – nnnnnn

1

您可以使用Object.keys,並通過使用一次Array.prototype.reduce循環,並列出了常見的按鍵 - 看演示如下:

var objectOne={boy:"jack",girl:"jill"}; 
 
var objectTwo={boy:"john",girl:"mary",dog:"mo"}; 
 

 
var result = Object.keys(objectOne).reduce(function(p,c){ 
 
    if(c in objectTwo) 
 
    p.push(c); 
 
    return p; 
 
},[]); 
 

 
console.log(result);

2

使用Object.keys

Object.keys(objectOne).filter(k => Object.hasOwnProperty.call(objectTwo, k)) 
+0

您的代碼可以在線性時間內以二次方式解決問題。不要在生產中這樣做! – kay

+0

這裏是線性的:P – sbedulin

+1

您應該使用'hasOwnProperty',因爲'null'和'undefined'可能是有效的值。 – kay

1

如果您想要找出哪些鍵匹配給定的兩個對象,你可以遍歷所有使用for... in循環的對象的鍵。在我的函數中,它將通過鍵循環並返回兩個對象中所有匹配鍵的數組。

let objectOne = { 
 
    boy: "jack", 
 
    girl: "jill" 
 
} 
 

 
let objectTwo = { 
 
    boy: "john", 
 
    girl: "mary", 
 
    dog: "mo" 
 
} 
 

 
function matchingKeys (obj1, obj2) { 
 
    let matches = []; 
 
    let key1, key2; 
 
    
 
    for (key1 in obj1) { 
 
    for (key2 in obj2) { 
 
     if (key1 === key2) { 
 
     matches.push(key1); 
 
     } 
 
    } 
 
    } 
 
    return matches 
 
} 
 

 
const result = matchingKeys(objectOne, objectTwo); 
 
console.log(result)

+0

@Kay - 除了'var','let'和未聲明以及因此全局變量的奇怪組合之外,我發現這很容易閱讀。 – nnnnnn

+0

@Kay謝謝你的反饋,你是對的,它可以做到線性時間。我試圖提高可讀性,但我保持原有解決方案的精神。 –

+0

@nnnnn謝謝你的反饋,我使我的變量保持一致。你最好 –

0

試試這個關於大小:

function compare(obj1, obj2) { 
    // get the list of keys for the first object 
    var keys = Object.keys(obj1); 

    var result = []; 

    // check all from the keys in the first object 
    // if it exists in the second object, add it to the result 
    for (var i = 0; i < keys.length; i++) { 
     if (keys[i] in obj2) { 
      result.push([keys[i]]) 
     }   
    } 

    return result; 
} 
相關問題