0

I have two objects that I am attempting to compare to see if their content is the same. The function I am writing should have these two objects equal true, however, I am struggling with how to sort these so I can test for equal content (it's out of order). How would I solve this?

const obj1 = {
  name: 'Sam',
  age: 27,
  description: [{
    eyes: 'blue',
    hair: 'brown'
  }]
} 

const obj2 = {
  age: 27,
  name: 'Sam',
  description: [{
    hair: 'brown',
    eyes: 'blue'
  }]
}
Alberto Trindade Tavares
  • 10,056
  • 5
  • 38
  • 46
FakeEmpire
  • 668
  • 1
  • 14
  • 35
  • 2
    Those are objects, not arrays. As such, the order [**is not guaranteed**](https://stackoverflow.com/a/5525820/2341603), and does not matter. You would need to loop over the keys for each to find out if they are equal. – Obsidian Age Jul 23 '17 at 23:10
  • 1
    _asked many times_ https://stackoverflow.com/questions/201183/how-to-determine-equality-for-two-javascript-objects – Axalix Jul 23 '17 at 23:15
  • _"The function I am writing should have these two objects equal true"_ Can you include what you have written at Question? What is the issue that you are having returning expected result? – guest271314 Jul 23 '17 at 23:26

1 Answers1

1

You can use isEqual, from Lodash, to perform deep comparison between objects:

const obj1 = {
  name: 'Sam',
  age: 27,
  description: [{
    eyes: 'blue',
    hair: 'brown'
  }]
} 

const obj2 = {
  age: 27,
  name: 'Sam',
  description: [{
    hair: 'brown',
    eyes: 'blue'
  }]
}

console.log(_.isEqual(obj1, obj2))
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
Alberto Trindade Tavares
  • 10,056
  • 5
  • 38
  • 46