0

I have already looked at this question, but I'm not looking for references. I'd like to know how to check if two objects, or two arrays, two maps, two sets, etc, have the same values as another.

Edit Not only the same values, but also keys!

For example;

var a = {foo: "bar"};
var b = {foo: "bar"};
a == b // I'd like true, but this returns false

Above code will return false, because of object reference.

I do know that "foo" == "foo" will return true, because that's how strings work, but how's that for objects, arrays, maps, etc?

Smally
  • 1,556
  • 1
  • 8
  • 27
  • Simple solution, `JSON.stringify(a) === JSON.stringify(b)`. Will not work if the keys are not in the same order. So a more indepth approach would be to loop over the keys and check against each one – Taplar Jul 03 '20 at 19:10
  • Oh, I will try that out! Thank you. ~~I do, however, would like to check for orders~~ I read that wrong, thought it wouldn't check for order. This worked brilliantly! – Smally Jul 03 '20 at 19:11
  • If you want to go that route, you would grab the `Object.keys(thing)` for each one; first make sure you have the same number of keys (if not then false), and then loop over the keys for one and verify that they exist in the other object and have the same value. – Taplar Jul 03 '20 at 19:12
  • @Smally: Don't rely on `stringify` for that. I don't know why people suggest it as a serious solution. If you want a value comparison, then do a value comparison manually. –  Jul 03 '20 at 19:16
  • I would try, but it would be a hassle to do that for arrays, maps, sets as well because I'm creating a unit test solution – Smally Jul 03 '20 at 19:17
  • Testing is always a hassle. IMO, that's not the place for convenient shortcuts. Defeats the purpose of testing. And you definitely can't do it if you're needing to include all those types. JSON represents a fairly small subset of the available types in JS. –  Jul 03 '20 at 19:26

0 Answers0