比较两个对象的值

时间:2019-03-07 16:28:00

标签: javascript

比较2个对象,并且仅当两个值相同时才返回true。如果它们大于两个相同的值,或者全部或全部不返回false。 示例:

A = {a: 1, b: 2, c: 3};
B = {a: 1, b: 5, c: 7};
C = {a: 1, b: 2, c: 7};

A和B应该返回true,因为A.a和B.a相同。 A和C应该返回false,因为A.a和C.a以及A.b和C.b相同。

到目前为止,我具有此功能:

Link

但是在这种情况下,const ObB7返回true,并且应该为false。

此功能可以简化吗?

function compareTwoObjects(ObA, ObB) {
  const { a, b, c } = ObA;
  const { a:d, b:e, c:f } = ObB;

  if (
    ((a === d && (a !== e && a !== f))
    || (a === e && (a !== d && a !== f))
    || (a === f && (a !== e && a !== d)))

    || ((b === d && (b !== e && b !== f))
    || (b === e && (b !== d && b !== f))
    || (b === f && (b !== e && b !== d)))

    || ((c === d && (c !== e && c !== f))
    || (c === e && (c !== d && c !== f))
    || (c === f && (c !== e && c !== d)))
  ) {
    return true;
  }
  return false;
}


const ObA = {a: 1, b: 2, c: 3};

const ObB0 = {a: 4, b: 5, c: 6};	// false
const ObB1 = {a: 4, b: 4, c: 4};	// false
const ObB2 = {a: 1, b: 1, c: 1};	// false
const ObB3 = {a: 2, b: 2, c: 2};	// false
const ObB4 = {a: 3, b: 3, c: 3};	// false
const ObB5 = {a: 1, b: 1, c: 7};	// false
const ObB6 = {a: 7, b: 2, c: 2};	// false
const ObB7 = {a: 7, b: 3, c: 3};	// false
const ObB8 = {a: 2, b: 3, c: 4};  // Should be false
const ObB9 = {a: 3, b: 7, c: 3};	// false

const ObB10 = {a: 5, b: 2, c: 3};	// true
const ObB11 = {a: 1, b: 5, c: 6};	// true
const ObB12 = {a: 0, b: 5, c: 3};	// true

console.log(compareTwoObjects(ObA, ObB0));
console.log(compareTwoObjects(ObA, ObB1));
console.log(compareTwoObjects(ObA, ObB2));
console.log(compareTwoObjects(ObA, ObB3));
console.log(compareTwoObjects(ObA, ObB4));
console.log(compareTwoObjects(ObA, ObB5));
console.log(compareTwoObjects(ObA, ObB6));
console.log(compareTwoObjects(ObA, ObB7));
console.log(compareTwoObjects(ObA, ObB8));
console.log(compareTwoObjects(ObA, ObB9));
console.log(compareTwoObjects(ObA, ObB10));
console.log(compareTwoObjects(ObA, ObB11));
console.log(compareTwoObjects(ObA, ObB12));

2 个答案:

答案 0 :(得分:2)

pip install Django

答案 1 :(得分:0)

您可以使用reduce

这里的想法是

  • 获取一个对象的键。
  • 如果每个键的两个对象的值相等,则op分别以1递增op,如果不是,则不作任何更改就直接返回op
  • 最后只检查op === 2是否返回true否则返回false

let A = {a: 1, b: 2, c: 3};
let B = {a: 1, b: 5, c: 7};
let C = {a: 1, b: 2, c: 7};

let compare = (a,b)=>{
  let op = Object.keys(a).reduce((op,inp)=>{
      if(a[inp] === b[inp]){
        op++
      } return op;
  },0)
  return op === 2 ? true : false
}

console.log(compare(A,B))
console.log(compare(A,C))
console.log(compare(C,A))