Thursday, July 15, 2021

Junior Developer Central JS Practice Exercise - 17

 
Question: 

Write a Javascript program to compare two objects to determine if the first one contains the same properties as the second one (which may also have additional properties)

for eg: 

const objA = { a: 1, b: 2, c: 1 }; 
const objB = { a: 1, b: 1, c: 1 };
const objC = { a: 1, b: 1, d: 1 };




Answer: 

function comTwoObj (obj1, obj2) {

const obj2Keys = Object.keys(obj2); 
return Object.keys(obj1).every(key => obj2Keys.includes(key));

}




> we declare a function 'comTwoObj' 
> it has 2 parameters 'obj1' & 'obj2' 
> we want to compare the keys of the two objects 'obj1' & 'obj2' 
> we do not want to compare the values, only the keys
> in our case the 'keys' are: a, b, c & so on
> we want to check if 'obj2' has all the keys of 'obj1' 
> 'obj2' can have additional keys as well, for eg: a, b, c, d, e & so on
> but it should have all the keys of 'obj1' 
> so first we create a variable 'obj2Keys' 
> we initialize it with a value we get by using the Object.keys() method on 'obj2'
> Object.keys() will return an array of a given object's property names or key names
> so our variable 'obj2Keys' will be an array of key names / property names of 'obj2'
> we then want to return true, if 'obj2Keys' includes all the key names of 'obj1' 
> however we cannot compare 'obj2Keys' to 'obj1' as 'obj2Keys' is an array
> so we use the Object.keys() method on 'obj1' as well 
> this method will return an array
> we also add the every() method on Object.keys(obj1)
> like this: Object.keys(obj1).every()
> the every() method returns true if all elements in an array pass a test
> the every method () executes the function once for each element present in the array
> so within the every () method we want to check if the array 'obj2Keys' includes all the elements in the array that is created [ when we use the '' Object.keys(obj1) '' ]
> so we use the includes() method to compare and check the two arrays
> this test will return 'true' if all elements of the array 'Object.keys(obj1) are included in 'obj2Keys'

No comments:

Post a Comment