2个对象/数组之间的Javascript混合比较

时间:2018-07-06 01:22:15

标签: javascript arrays object javascript-objects

我有2个不同的javascript对象:

key = {
  id : 3, 
  name : "Leroy", 
  class : "A", 
  address : "IDN", 
  age : "17"
}

和...

answer = {
  id : 3, 
  class : "A", 
  name : "Leroy", 
  age : "17", 
  address : "IDN"
}

我想做的是使用(===)或(==)将答案对象与键对象进行比较,即使答案对象键顺序混合,也将返回 true ,但是只要每个键中的值相同,它仍将返回 true

如果答案对象中的键之一及其​​值不存在,或者答案对象中设置了新的键和值,则条件将返回 false

任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:0)

key = {
  id : 3, 
  name : "Leroy", 
  class : "A", 
  address : "IDN", 
  age : "17",
}

answer = {
  id : 3, 
  class : "A", 
  name : "Leroy", 
  age : "17", 
  address : "IDN"
}

   newanswer = {
  newid : 3, 
  class : "A", 
  name : "Leroy", 
  age : "17", 
  address : "IDN"
}

console.log(isequal(key,answer))
   console.log(isequal(key,newanswer ))

function isequal(prev, now) {
    var prop;
    for (prop in now) {
        if (!prev || prev[prop] !== now[prop]) {
            return false;
        }
    }
    return true; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:0)

有关更多信息,请参见Object.entries()Object.keys()Array.prototype.every()

// Input.
const original = {id: 3, name: "Leroy", class: "A",address: "IDN", age: "17"}
const unordered = {id: 3, class: "A", name: "Leroy",age: "17",address: "IDN"}
const different = {id: 4,class: "B",name: "Lerox",age: "18",address: "IDP"}

// Is Match.
const isMatch = (A, B) => {
  const eA = Object.entries(A)
  return eA.length === Object.keys(B).length // Equivalent number of keys.
  && eA.every(([k, v]) => B[k] === v) // B contains every key + corresponding value in A.
}

// Proof.
console.log(isMatch(original, unordered)) // true
console.log(isMatch(original, different)) // false

答案 2 :(得分:0)

const keys = (o) => Object.keys(o).sort((a, b) => a > b)
const isEqual = (key, answer) => {
  let keyArr = keys(key)
  let keyLen = keyArr.length
  let answerArr = keys(answer)
  if (keyLen !== answerArr.length) return false
  for (let i = 0; i < keyLen; i++) {
    if (key[keyArr[i]] !== answer[answerArr[i]]) return false
  }
  return true
}