0

I have 2 different javascript object :

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

and ...

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

What I wanted to do is to compare answer object with key object using (===) or (==) and will return true, even when the answer object key order is mixed, but as long as the value within each key is the same, it will still return true.

The condition will return false if one of the key in answer object and its value is not present, or there is a new key and value set inside the answer object.

Any help would be appreciated!

Hilal Arsa
  • 171
  • 1
  • 3
  • 15
  • I'm new here, and i found the answer from the duplicates (thanks). Should I posted it somewhere or just embed the link to it? Or not? – Hilal Arsa Jul 06 '18 at 02:44

3 Answers3

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>
Sangram Nandkhile
  • 17,634
  • 19
  • 82
  • 116
0

See Object.entries(), Object.keys(), and Array.prototype.every() for more info.

// 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
Arman Charan
  • 5,669
  • 2
  • 22
  • 32
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
}
Tony_zha
  • 97
  • 6