可以說有兩個對象,但一個對象的屬性與另一個不同。有沒有辦法找出哪些屬性匹配?如何檢查兩個對象屬性是否匹配?
例如:
var objectOne = {
boy: "jack",
girl: "jill"
}
var objectTwo = {
boy: "john",
girl: "mary",
dog: "mo"
}
編輯:應該告訴我boy
和girl
屬性名在兩個對象中找到。
可以說有兩個對象,但一個對象的屬性與另一個不同。有沒有辦法找出哪些屬性匹配?如何檢查兩個對象屬性是否匹配?
例如:
var objectOne = {
boy: "jack",
girl: "jill"
}
var objectTwo = {
boy: "john",
girl: "mary",
dog: "mo"
}
編輯:應該告訴我boy
和girl
屬性名在兩個對象中找到。
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
的條件/身體根本補充。
您可以使用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);
Object.keys(objectOne).filter(k => Object.hasOwnProperty.call(objectTwo, k))
如果您想要找出哪些鍵匹配給定的兩個對象,你可以遍歷所有使用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)
@Kay - 除了'var','let'和未聲明以及因此全局變量的奇怪組合之外,我發現這很容易閱讀。 – nnnnnn
@Kay謝謝你的反饋,你是對的,它可以做到線性時間。我試圖提高可讀性,但我保持原有解決方案的精神。 –
@nnnnn謝謝你的反饋,我使我的變量保持一致。你最好 –
試試這個關於大小:
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;
}
您的例子沒有表現出很大的。你什麼意思? – Li357
所以你想要一個屬性*名稱*在兩個對象中的列表,而不考慮它們的*值*是什麼?我們應該假設沒有物體嵌套? – nnnnnn
@ nnnnnn。對,就是這樣。 – Deke