2

Using underscore.js I am trying to compare two objects against each other and if they are they same I want to return true. To accomplish this I am using _.isEqual().

var a = {0: "2", 1: "11", 2: "1"}
var b = {0: "2", 1: "11", 2: "1"}
_.isEqual(a, b) // returns true

That works as expected. The issue I am running into is when I might not have all the data from one of the objects at a given time. Let's use this example:

var a = {0: "2", 1: undefined, 2: undefined}
var b = {0: "2", 1: "11", 2: "1"}
_.isEqual(a, b) // returns false

I would like a way (obviously not using ._isEqual) for that to return true if some of the values compared are undefined. Any Ideas?

2
  • So _.isAlmostEqual()? If you're dealing only with simple, non-nested objects like the ones shown you could write your own comparison function with only about four lines of code. If you want to allow for nested objects I'm sure you could take one of the existing solutions (including Underscore's) and modify it to ignore undefined properties. Commented Aug 26, 2016 at 6:21
  • I don't think that's an underscore method... haha Commented Aug 26, 2016 at 6:23

1 Answer 1

2

Here's one solution that first works out which common keys have defined values and then uses _.isEqual to make the comparison:

var a = {0: "2", 1: undefined, 2: undefined}
var b = {0: "2", 1: "11", 2: "1"}

// helper predicate that returns true if the value passed to it is undefined
var notUndefined = _.negate(_.isUndefined);

// find the common keys that have defined values
var keys = _.intersection(_.keys(_.pick(a,notUndefined)), _.keys(_.pick(b,notUndefined)))

// compare only the common keys
var result = _.isEqual( _.pick(a, keys), _.pick(b, keys) );

NB This will only work if your objects contain primitive types (no nested objects or arrays)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.