How to assert partially deep equal / compare objects in javascript?

I have an API, and I want to claim that the expected data is returned. I don't care if more data is returned.

Therefore, I want to compare two objects ( expected and actual ), where all expected attributes should be equal to actual , but actual can contain more attributes:

 var expected = { foo: 1, bar: { x1: 42, a1: [ 1, 2, { x: 7 } ] } } var actual = { foo: 1, whatever: 55, // to be ignored additional: { // to be ignored ignore: 1 }, bar: { x1: 42, a1: [ 1, 2, { x: 7, y: 8 // to be ignored } ] } } partiallyEqual(expected, actual) // returns true 

Some more examples:

 partiallyEqual({x: 1}, {a:2, x:1}) // return true partiallyEqual({x: 1}, {a:2, x:2}) // return false (x is different) 

Arrays can (optionally) undergo a partial equivalent if actual contains additional elements.

 partiallyEqual([1, 3], [1, 2, 3]) // return true partiallyEqual([3, 1], [1, 2, 3]) // return false (different order) 
+5
source share
2 answers

I use this recursive function that I wrote some time ago:

 Object.prototype.equals = function(to) { for (var prop in to) { if (this.hasOwnProperty(prop) && to.hasOwnProperty(prop)) { if (to[prop] && typeof this[prop] == "object" && typeof to[prop] == "object") { if (!this[prop].equals(to[prop])) { return false } } else if (this[prop] != to[prop]) { return false } } } return true; }; ({ x: { a: 1, b: 2 } }).equals({ x: { a: 1, b: 2 } }) => true ({ x: { a: 1, b: 2 } }).equals({ x: { a: 1, b: 1 } }) => false ({ x: [1,2] }).equals({ x: { 1:1,2:2 } }) => true (doesn't differentiate between array and/or object) 

This function will return false as soon as there is some difference in the old vs new object. A new object can contain anything if it has all the properties of an old object.

0
source

A deep equal can be difficult for different cases, for example NaN !== NaN , and there can be circular links. Recently, I wrote a simple peer review function with recursive and circular link checking, and it should be pretty straight forward. You can simply ignore the length check part to do partial execution.

Source code on github: https://github.com/ryancat/simple-deep-equal

0
source

All Articles