Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find if an object is subset of another object in javascript

Tags:

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 
like image 980
kkrishnaai Avatar asked Mar 02 '16 02:03

kkrishnaai


People also ask

How to get a subset of an object in js?

To get the subset of properties of a JavaScript Object, we make use of destructuring and Property Shorthand. The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

How do you check if an object contains another object JavaScript?

The hasOwnProperty() method will check if an object contains a direct property and will return true or false if it exists or not. The hasOwnProperty() method will only return true for direct properties and not inherited properties from the prototype chain.

Can an object contain another object JS?

A JavaScript Object is a collection of Key-Value pairs, and nested objects are objects that have other objects inside them as their property.

How do I extract properties from an object?

We have to write a JavaScript function, say extract() that extracts properties from an object to another object and then deletes them from the original object.


1 Answers

Using Lodash isMatch

_.isMatch({prop: 'object', id: 3}, {prop: 'object'})

Performs a partial deep comparison between object and source to determine if object contains equivalent property values.

like image 57
BitOfUniverse Avatar answered Sep 30 '22 19:09

BitOfUniverse