0
var i={ key1:value1, key2:value2 }
var j={ key2:value2, key1:value1 }

How to compare above objects and get answer true?

Srini
  • 111
  • 1
  • 8
  • https://stackoverflow.com/questions/62405551/how-to-compare-objects-using-lodash-regardless-on-their-order – Joe Jun 19 '21 at 12:48
  • 3
    Does this answer your question? [How to determine equality for two JavaScript objects?](https://stackoverflow.com/questions/201183/how-to-determine-equality-for-two-javascript-objects) – thelovekesh Jun 19 '21 at 12:50
  • The object doesn´t have any kind of order between elements. Just only arrays – alejoko Jun 19 '21 at 12:50
  • this test can only be done with javascript code, it will be more or less complex depending on the types of sub-elements contained, their depth of sub-objects, etc ... – Mister Jojo Jun 19 '21 at 12:56

3 Answers3

3

You could sort the object keys and compare

var i = {
  key1: 'value1',
  key2: 'value2'
}
var j = {
  key2: 'value2',
  key1: 'value1'
}

console.log(JSON.stringify(sortedObject(i)) === JSON.stringify(sortedObject(j)))


function sortedObject(unordered) {
  return Object.keys(unordered).sort().reduce(
    (obj, key) => {
      obj[key] = unordered[key];
      return obj;
    }, {});
}
Jeevan HS
  • 163
  • 6
2

Compare Keys

var i={ key1:"value1", key2:"value2"}
var j={ key2:"value2", key1:"value1" }
for(k in i) {
  for(p in j) {
     console.log(k == p)
  }
}

Compare Values

var i={ key1:"value1", key2:"value2"}
var j={ key2:"value2", key1:"value1" }
for(k in i) {
  for(p in j) {
     console.log(i[k] == j[p])
  }
}
JS_INF
  • 467
  • 3
  • 10
0

For this purpose, you can use lodash library. You're looking for a method called isEqual.

In the example below, you can see that I passed the objects from your example and this code returns true. You can play around with the code right here (online lodash tester).

var i={ key1: '13', key2: 140 }
var j={ key2: 140, key1: '13' }

_.isEqual(i, j) // returns true