user2412285 user2412285 - 2 months ago 7
Javascript Question

Find if an object is subset of another object in javascript

I need a function isSubset, which when given two objects compares its values and tell if one object is subset of another.

object1 = { pickUpLocation : {city : 'Hyderabad', state: 'Telangana' }};
object2 = { dist : 322, pickUpLocation: {city : 'Hyderabad', state: 'Telangana' }};




isSubset(object1, object2); //should return true




object3 = { pickUpLocation : {city : 'Chennai', state: 'Telangana' }}
object4 = { dist : 322, pickUpLocation: {city : 'Hyderabad', state: 'Telangana' }}




isSubset(object3, object4) //should return false as city's value is different

Answer

In English:

Is there some key in object2 which satisifies the condition that there is deep equality between its value and object1?

Write that out:

_.some(                       // Is there some key
  object2,                    // in object2
  function(val) {             // which satisfies the condition that
    return _.isEqual(         // there is deep equality between
      val,                    // its value and
      object1                 // object1?
    );
  }

In shorter form:

_.some(object2, function(val) { return _.isEqual(val, object1); })

In ES6:

_.some(object2, val => _.isEqual(val, object1))

My suggestion is to read through the lodash docs and learn all the APIs, or at least the main ones. For example, this problem will be very difficult to solve on your own if you are not aware of important routines such as _.some and _.isEqual. On the other hand, if you do know them, then it is quite trivial.