我有两个不同的对象,如果第二个对象的至少一个属性与第一个对象匹配,我想返回true。如果不是,则返回false。我已经尝试过.hasOwnProperty和.keys方法,但是无法处理。这是下面的示例代码。谢谢。
let propchecker = (a,b) =>{
if(/* at least one property matches exact */){
return true;
}
else {
return false;
}
}
let origin = {name: "John", surname: "Doe"};
let first = {name: "John", surname: "Roe" };
let second = {name: "Jane", surname: "Doe"};
let third = {name: "Richard", surname: "Roe"};
console.log(propchecker(origin,first)); //Should return True.
console.log(propchecker(origin,second)); //Should return True.
console.log(propchecker(origin,third)); //Should return False.
答案 0 :(得分:1)
您可以使用Object.keys()
获取一个对象的键,然后在其上使用some()
。
let propchecker = (a,b) => Object.keys(a).some(x => a[x] === b[x])
let origin = {name: "John", surname: "Doe"};
let first = {name: "John", surname: "Roe" };
let second = {name: "Jane", surname: "Doe"};
let third = {name: "Richard", surname: "Roe"};
console.log(propchecker(origin,first)); //Should return True.
console.log(propchecker(origin,second)); //Should return True.
console.log(propchecker(origin,third)); //Should return False.
答案 1 :(得分:1)
可能有更短的解决方案,但这很好用
let propchecker = (a,b) =>{
for (let key in a) {
for (let key2 in b ){
if(a[key] == b[key2]){
return true
}
}
}
return false
}
let origin = {name: "John", surname: "Doe"};
let first = {name: "John", surname: "Roe" };
let second = {name: "Jane", surname: "Doe"};
let third = {name: "Richard", surname: "Roe"};
console.log(propchecker(origin,first)); //Should return True.
console.log(propchecker(origin,second)); //Should return True.
console.log(propchecker(origin,third)); //
答案 2 :(得分:0)
尝试一下
let propchecker = (a,b) =>{
result = false;
for(let ele in first){
result = result || (a[ele] === b[ele])
}
return result
}
let origin = {name: "John", surname: "Doe"};
let first = {name: "John", surname: "Roe" };
let second = {name: "Jane", surname: "Doe"};
let third = {name: "Richard", surname: "Roe"};
console.log(propchecker(origin,first)); //Should return True.
console.log(propchecker(origin,second)); //Should return True.
console.log(propchecker(origin,third)); //Should return False.
答案 3 :(得分:0)
看起来它已经被回答了,但我也将帽子戴在戒指里。所有这些答案几乎都在做同一件事。
let propchecker = (a,b) =>{
var check = false;
Object.keys(a).forEach(function(key) {
if(a[key] == b[key]) {
check = true;
}
})
return check;
}
let origin = {name: "John", surname: "Doe"};
let first = {name: "John", surname: "Roe" };
let second = {name: "Jane", surname: "Doe"};
let third = {name: "Richard", surname: "Roe"};
console.log(propchecker(origin,first)); //Should return True.
console.log(propchecker(origin,second)); //Should return True.
console.log(propchecker(origin,third)); //Should return False.